skip to content

In a Rails 8.1 api_only app, how do you add cookie-based sessions back, and why does the order of the config lines matter?

level: middleimportance: should knowfreq 30%

answer

  1. api_only removes two middleware
  2. DisabledSessionError on write
  3. config.session_store with a key
  4. ActionDispatch::Cookies before the store
  5. pass config.session_options along

basics

~10 s

An api_only app has no ActionDispatch::Cookies or session store, so writing session raises DisabledSessionError. In config/application.rb set config.session_store, then use ActionDispatch::Cookies and config.session_store with config.session_options, in that order.

solid answer

~30 s

With `config.api_only = true` the default stack omits `ActionDispatch::Cookies` and the session store, so `session[:user_id] = 1` raises `ActionDispatch::Request::Session::DisabledSessionError`. To add sessions back you edit `config/application.rb`: first `config.session_store :cookie_store, key: "_tracker_session"`, which also fills `config.session_options`; then `config.middleware.use ActionDispatch::Cookies`; then `config.middleware.use config.session_store, config.session_options`. Order matters twice: the arguments are read when that line runs, so the store must be configured above it, and the cookies middleware must sit before the store that reads and writes through it. A bare `use ActionDispatch::Session::CookieStore` would ignore your options and fall back to the `_session_id` key. Controllers that call `cookies` also need `include ActionController::Cookies`.

code

ruby · 11 lines
ruby
# config/application.rb
module TrackerApi
  class Application < Rails::Application
    config.load_defaults 8.1
    config.api_only = true

    config.session_store :cookie_store, key: "_tracker_session"
    config.middleware.use ActionDispatch::Cookies
    config.middleware.use config.session_store, config.session_options
  end
end

go deeper

for a junior

Know that API mode has no sessions by default and that writing session raises an error until a store is configured.

for a middle

Write the three config lines in order and explain what each one does and why session_options must be passed explicitly.

for a senior

Decide when cookie sessions belong in an API at all, and list the CSRF and cross-site cookie obligations they bring.

for a principal

Weigh one API serving both cookie and token clients against a separate backend-for-frontend for the browser app.

## Why sessions disappear in API mode A **session** in Rails is a hash that survives between requests. With the default **cookie store** its contents are encrypted into a cookie the browser sends back each time. Two middleware make that work: - **`ActionDispatch::Cookies`** builds the request's cookie jar and writes any changed cookies onto the response as `Set-Cookie` headers. - **The session store** (for example `ActionDispatch::Session::CookieStore`) loads the session from a cookie when the app first touches it and saves it back through the jar. When `config.api_only = true`, Rails' default middleware stack skips both, along with `ActionDispatch::Flash`. Token-authenticated mobile clients never needed them. But the session accessor still exists on every request, so code does not crash until it writes: ```ruby session[:user_id] # => nil session[:user_id] = user.id # ActionDispatch::Request::Session::DisabledSessionError: # Your application has sessions disabled. To write to the session # you must first configure a session store ``` ## The three lines, in order You put them in `config/application.rb`, inside the application class: ```ruby config.session_store :cookie_store, key: "_tracker_session" config.middleware.use ActionDispatch::Cookies config.middleware.use config.session_store, config.session_options ``` 1. **`config.session_store :cookie_store, key: ...`** records the store and its options. Read back without arguments, `config.session_store` resolves the symbol to the middleware class, and `config.session_options` returns the options hash. 2. **`config.middleware.use ActionDispatch::Cookies`** appends the cookie middleware. 3. **`config.middleware.use config.session_store, config.session_options`** appends the store, passing your key and any other options. ## Why the order matters | Mistake | What happens | |---|---| | Store line above the `config.session_store :cookie_store` call | `config.session_store` still returns nil when the arguments are evaluated, so nil is registered as a middleware and the app fails to boot | | `use ActionDispatch::Session::CookieStore` with no options | sessions work, but your options are ignored and the cookie key defaults to `_session_id` | | Store added, `ActionDispatch::Cookies` missing or after it | the store has no working cookie jar to read from and write to, so the session never persists | The deeper reason is that a full app gets this wiring for free: the default stack passes `config.session_options` to the store automatically whenever `api_only` is false. In API mode you are rebuilding that step by hand, and `config.middleware.use` captures its arguments at the moment the line runs. ## The controller side The middleware gives every request a working session, and `session` is available on any controller because `ActionController::Metal` delegates it to the request. Two more pieces are optional: - `include ActionController::Cookies` if controllers call `cookies.signed[...]` or `cookies.encrypted[...]` directly. - `config.middleware.use ActionDispatch::Flash` plus `include ActionController::Flash` if you want `flash`, which is rare in an API. ## When this is the right call Adding sessions back makes sense when one client is a **browser single-page app** that you would rather authenticate with an HTTP-only cookie than with a token kept in JavaScript. It brings obligations other topics own: - A cookie-authenticated API must defend against cross-site request forgery, and `ActionController::API` does not include forgery protection. - An SPA on a different site needs the cookie's `same_site:` and `secure:` options and credentialed CORS set to match. - The mobile app can keep sending a token; one API can accept both, checked in a shared `before_action`. ## Verifying the wiring After restarting the server, check the result instead of trusting the config: 1. Run `bin/rails middleware` and confirm `ActionDispatch::Cookies` appears, followed by `ActionDispatch::Session::CookieStore`, near the end of the list. 2. In an integration test, sign in and make a second request; the second must see the user: ```ruby post api_v1_session_path, params: { session: { email_address: "[email protected]", password: "secret123" } }, as: :json get api_v1_profile_path, as: :json assert_response :success ``` 3. Inspect the `Set-Cookie` header of the first response: the cookie name should be `_tracker_session`, not `_session_id`. A `_session_id` cookie is the tell-tale sign that the store was added without `config.session_options`.

  • In an api_only app with no session middleware, what does reading session[:user_id] return?
    It returns nil. The request falls back to a disabled session object that reports nothing stored, so reads quietly return nil. Only writes raise `ActionDispatch::Request::Session::DisabledSessionError`, which is why a login action is usually where the missing middleware first shows up.
  • Can the same api_only app serve a mobile client with tokens and a browser SPA with cookies?
    Yes. The middleware runs for every request, but a client that never sends the session cookie simply gets an empty session. A shared `before_action` can look for an `Authorization` token first and fall back to `session[:user_id]`. The cookie path then needs forgery protection and credentialed CORS, which the token path does not.

  • Reading session in an api_only app raises DisabledSessionError.
  • A config/initializers/session_store.rb file alone restores sessions in API mode.
  • ActionDispatch::Cookies can come after the session store in the stack.
  • use ActionDispatch::Session::CookieStore with no options keeps the app's session key.
  • Including ActionController::Cookies adds the cookie middleware automatically.