How do you add a custom http header?

I'm looking to add custom http headers to a Ruby on Rails app that is currently hosted on Heroku.


Solution 1:

Use:

response.headers['HEADER NAME'] = 'HEADER VALUE'

either in a specific method or to a before_filter method of your application controller depending on whether you need this to be added in a specific or to all of your responses.

UPDATE for Rails 5 - February 24th, 2018

As noted by @BrentMatzelle in the comments, for Rails 5:

response.set_header('HEADER NAME', 'HEADER VALUE')

Solution 2:

In rails 5, the following solution works (in action methods)

response.set_header("Header-Name", "Header value")

Reference: edgeapi

Solution 3:

In Rails 3 or above, simply

headers['Header-Name'] = 'header value'

works in controllers. This is even the recommended way; according to the documentation,

Response is mostly a Ruby on Rails framework implementation detail, and should never be used directly in controllers. Controllers should use the methods defined in ActionController::Base instead. For example, if you want to set the HTTP response’s content MIME type, then use ActionController::Base#headers instead of Response#headers.

And this is still true in Rails 6.0.