Cookies and Sessions

arbarrington

arbarrington

Posted on October 20, 2022

Cookies and Sessions

Since cookies are such an important part of most web applications, Rails has excellent support for cookies and sessions baked in. Unfortunately for us, when you create a new application in API mode with rails new appname --api, the code needed for working with sessions and cookies in the controller is excluded by default.

To add session and cookie support back in, we need to update our application's configuration in the config/application.rb file:

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.load_defaults 6.1
    # This is set in apps generated with the --api flag, and removes session/cookie middleware
    config.api_only = true

    # Must add these lines!
    # Adding back cookies and session middleware
    config.middleware.use ActionDispatch::Cookies
    config.middleware.use ActionDispatch::Session::CookieStore

    # Use SameSite=Strict for all cookies to help protect against CSRF
    config.action_dispatch.cookies_same_site_protection = :strict
  end
end
Enter fullscreen mode Exit fullscreen mode

This will add in the necessary middlewareLinks to an external site. for working with sessions and cookies in our application.

To access the cookies hash in our controllers, we also need to include the ActionController::Cookies module in our ApplicationController:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  include ActionController::Cookies
end
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
arbarrington
arbarrington

Posted on October 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related