Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Session Lookup for a single controller action

I want to disable sessions completely for a controller action, because I want this single controller action (it's an autocomplete action on thousands of values, so speed matters) to be blazingly fast.

I tried using session_off, but it just sets the session variable to nil, an still looks up the users session in the database.

Is it possible to completely disable the Rails::SessionStore middleware, but only for a single controller action or URL?

I am running rails 3.2.17.

like image 225
iblue Avatar asked Dec 06 '25 02:12

iblue


2 Answers

Rails 5+ solution (maybe before, not sure when this became available).

Add this to your controller. You can specify which actions should not touch/update the session using the only: option.

after_action -> { request.session_options[:skip] = true }, only: :my_action_name

This will make the response not include the set_cookie response header. I found this particularly useful when dealing with a race condition in multiple AJAX requests, whereas one contained a very important session (cookie data) update and the other the session was not used, but Rails still sent back an updated cookie for the session. The race condition could cause the updated session data from the important action to be overwritten from the one I didn't care about.

like image 154
Ryan Avatar answered Dec 08 '25 16:12

Ryan


The answer is: handle this endpoint in a Rack middleware of your own, and insert it into the stack as early as possible!

You can achieve this in config/routes.rb just by routing to the middleware object:

match 'my_autocomplete_endpoint', to: AutocompleteMiddleware

then just return a response from the middleware and don't go up the stack.

You can put this wherever you want in the stack in config/application.rb with:

config.middleware.insert_before(SomeOtherMiddleware, AutocompleteMiddleware)

e.g., perhaps insert it before Rails::SessionStore.

like image 32
gregates Avatar answered Dec 08 '25 16:12

gregates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!