Search code examples
rubysinatrarackthinfiber

Sinatra session not preserved with Rack::FiberPool


The session is not preserved between requests, though I can't see what I'm doing wrong. Code!

require 'sinatra'
require 'rack/fiber_pool'

class SessionTest < Sinatra::Base
  use Rack::FiberPool
  enable :sessions
  set :session_secret, "foobar"

  get '/' do
        body { session.inspect } #This is always '{}'!
  end

  get '/a' do
    session['user'] = "bob"
    redirect '/'
  end
end

run SessionTest.new

Solution

  • Try this instead:

    require 'sinatra'
    require 'rack/fiber_pool'
    
    class SessionTest < Sinatra::Base
      enable :sessions
      set :session_secret, "foobar"
    
      get '/' do
            body { session.inspect } #This is always '{}'!
      end
    
      get '/a' do
        session['user'] = "bob"
        redirect '/'
      end
    end
    
    use Rack::FiberPool
    run SessionTest.new
    

    Otherwise Sinatra will set up the fiber pool after the session middleware, which doesn't work. This is not a bug but caused by the way Rack::FiberPool works.