November 3, 2018; in Ruby on Rails

Custom headers for HTTP statuses in Ruby on Rails

Adding headers for specific HTTP statuses in Ruby on Rails can be easily accomplished using super for render.

In your app/controllers/application_controller.rb:

def render(*args)
  super.tap do 
    if (400..599).cover?(response.status)
      response.headers['X-Custom-Error'] = '1'

There’s a lot you can do with this. As your application grows in complexity, using this pattern can help you communicate between your app and things like a reverse proxy.