Sinatra session members "disappearing" Sinatra session members "disappearing" heroku heroku

Sinatra session members "disappearing"


Hard to see what is going on without knowing all details, but there is a simple rule that you are most probably violating: do not use http caching on actions that are supposed to do something (other than just show page). When http caching is on, you browser does not even try to re-load the page and renders it from browser cache.

Cookies are not cached anywhere, the only thing cache_control does is setting CacheControl http response value

In your case the best thing you can do is to add list of routes that have no-action pages to your before block:

before '/my/static/page' do  cache_control :public, :must_revalidate, :max_age => 60end

Most probably you will have very limited set of routes where you can benefit from http caching


A chap by the name of Ari Brown (waves at Ari), who is not a member here but deserves the credit for this answer, pointed me at the right solution, which is, as per the Sinatra FAQ, to not use enable :sessions but to use Rack::Session::Cookie as per

use Rack::Session::Cookie, :key => 'rack.session',                           :domain => 'foo.com',                           :path => '/',                           :expire_after => 2592000, # In seconds                           :secret => 'change_me'

I've added this into my config.ru and all is well.

I also noticed over in this post the alternative suggestion to set :session_secret, 'change_me' and, indeed, to do this via an environment variable, namely:

$ heroku config:add SESSION_KEY=a_longish_secret_key

then in your app

enable :sessionsset :session_secret, ENV['SESSION_KEY'] || 'change_me'

Obviously you can use the environment variable strategy with the Rack::Session::Cookie approach too. That's the way I went as it offers more flexibility in configuration.

The reason these work is that the cache controller middleware is farming requests out to multiple server instances and without setting a session secret it's just making one up per server, and thus breaking the sessions.