Strip cookies from response

Once in a while you might find yourself looking for a simple and flexible solution to deal with HTTP responses from your app. One of the cases - add, modify or remove specific HTTP headers from response. The fastest way is to write custom Rack middleware, since most of ruby web frameworks are built on top of it.

One particular case: Sinatra app that uses rack-based sessions. Each response will have a 'Set-Cookie' header, which is not necessary if you're writing some embedding functionality (widgets, etc).

Cookie-killing middleware:

module Rack
  class StripCookies
    attr_reader :paths

    def initialize(app, options={})
      @app   = app
      @paths = options[:paths] || []
    end

    def call(env)
      status, headers, body = @app.call(env)
      if @paths.include?(env['REQUEST_PATH'])
        headers.delete('Set-Cookie')
      end
      [status, headers, body]
    end
  end
end

Now, lets use it. Just add a few lines to config.ru:

use Rack::StripCookies, :paths => ['/embed/widget', '/embed/button']
run Sinatra::Application

So, basically every route that is listed in paths will be clean from Set-Cookie header. You can implement whatever logic that matches your needs.