Why doesn't session[:] work in grape - rails?
Asked Answered
E

1

5

I'm using Rails with Grape as API. I was just curious why there isn't session[:something] method in grape? I can create cookies but can't created signed cookies either. It throw me an error.

Earleanearleen answered 11/2, 2016 at 16:1 Comment(0)
C
14

Grape is a lightweight framework for building API's and when you send a request to the Grape API endpoint, the response doesn't go through all the Rails middlewares instead it goes through a thin set of Rack middlewares. Therefore Grape is specially designed for building API's where you can plug in the required middlewares that you want depending on your requirements. The main goal is to make the API as lightweight as possible and for efficient speed and performance.

If you want to enable session in Grape which is mounted on Rails you need to use the ActionDispatch::Session::CookieStore middleware.

class API < Grape::API
  use ActionDispatch::Session::CookieStore

  helpers do
   def session
     env['rack.session']
   end
  end

  post :session do
   session[:foo] = "grape"
  end

  get :session do
    { session: session[:foo] }
  end
end

You can use the grape_session gem for the above purpose.

If you want the default way of using session in a Rack application without the Rails middlewares use the default Rack::Session::Cookie middleware available in Rack.

Cachet answered 16/2, 2016 at 9:4 Comment(2)
If you want to 'share' the session with Rails you'll need to specify the key too like this: use ActionDispatch::Session::CookieStore, key: '_XXX_session'Forklift
If you are using xhr to send requests to your api endpoint, make sure cookies are present in request headers.Emanuele

© 2022 - 2024 — McMap. All rights reserved.