Search code examples
ruby-on-railsherokuasset-pipeline

Setting Custom Headers for Assets in Rails on Heroku Cedar


I have a cedar application that uses Rails 4.0 and the asset pipeline. I'd like to set custom headers for all assets from the asset pipeline. How can this be done?


Solution

  • An easy way would be to use a rack plugin, something like this:

    class RackAssetFilter
       def initialize app
          @app = app
       end
    
       def call env
          @status, @headers, @body = @app.call env
          if env['PATH_INFO'].starts_with?( "/assets/" )
             @headers['X-Header-1'] = 'value'
             # ... 
          end
          return [@status, @headers, @body]
       end
    end
    

    To enable it, in application.rb:

    config.middleware.insert_before( ActionDispatch::Static, RackAssetFilter )
    

    Keep in mind you need to declare or load the RackAssetFilter via require before you insert it into the middleware stack in application.rb