In a Rails 8.1 app with default settings, where does session[:basket_id] = @basket.id actually store the value?
answer
- the browser holds it
- one cookie named _app_session
- encrypted with a secret_key_base key
- JSON round trip on every request
- about 4 KB for the whole hash
basics
~20 sIn the browser. The default session store is :cookie_store, so Rails serializes the whole session hash to JSON, encrypts it with a key derived from secret_key_base and sends it as one cookie, _yourapp_session, that comes back on every request.
solid answer
~40 sWith no `config.session_store` line, Rails 8.1 installs `:cookie_store` with the key `_<app_name>_session`. `session[:basket_id] = @basket.id` writes into a hash that, at the end of the request, is serialized (JSON under load_defaults 7.0 and later), encrypted and authenticated with AES-256-GCM using a key derived from `secret_key_base`, and set as that cookie. The browser cannot read or alter it, but it holds the data, sends it on every request, and the whole cookie must fit in 4096 bytes or Rails raises `ActionDispatch::Cookies::CookieOverflow`. So store small values, an id rather than the `Basket` record: top-level keys come back as strings, and anything nested must survive a JSON round trip.
code
ruby · 13 linesclass BasketsController < ApplicationController
def show
@basket = current_basket
end
private
def current_basket
Basket.find_by(id: session[:basket_id]) || Basket.create!.tap do |basket|
session[:basket_id] = basket.id
end
end
endgo deeper
Recall that session[] persists small values between requests, that the default store is an encrypted cookie, and that you store an id rather than a whole record.
Explain the serialize, encrypt, size-check sequence, the _app_session key, the JSON round trip of keys and values, and why a bad cookie reads as an empty session.
Show you keep session data tiny and server-owned state in tables, and know a client-held cookie can be replayed until it expires or the secret rotates.
Weigh the stateless cookie default against server-side stores for revocation and size, and plan secret rotation so a key change does not sign everyone out.
## The default store A bakery pre-order app keeps a customer's basket between requests. The controller does: ```ruby basket = Basket.create! session[:basket_id] = basket.id ``` `session` is a hash-like object on the request. Where the data goes depends on `config.session_store`. A new Rails 8.1 app does not set it, so a Rails initializer installs the default: ```ruby config.session_store :cookie_store, key: "_bakery_session" ``` The key is `_<app name>_session`, derived from the application class. With `:cookie_store` there is **no server-side session record**: the session hash itself is the cookie. ## What happens at the end of the request 1. **Serialize.** The session hash, plus an internal `session_id` and any flash entries, is turned into a string. Under `load_defaults` 7.0 and later, including 8.1, `config.action_dispatch.cookies_serializer` is `:json`. 2. **Encrypt and authenticate.** The session store writes through the request's **encrypted cookie jar**, which uses AES-256-GCM with a key derived from `secret_key_base`. Since the 6.0 defaults the message also carries a **purpose** naming the cookie, so a value cannot be moved into another cookie. 3. **Size check.** If the cookie's name plus its encrypted, encoded value exceeds **4096 bytes**, Rails raises `ActionDispatch::Cookies::CookieOverflow`. 4. **Set-Cookie.** The browser stores it and sends it back on **every request** to the app, assets included. On the next request Rails decrypts the cookie; if it fails to decrypt or verify, the session is simply **empty**, not an error. ## What that means for the values you store | Store | Comes back as | |---|---| | `session[:basket_id] = 42` | `42` (read with `session[:basket_id]` or `session["basket_id"]`) | | a Symbol, such as `:pickup` | the String `"pickup"` | | a Time | a String | | `{ items: [1, 2] }` | `{ "items" => [1, 2] }`, so `session[:basket][:items]` is `nil` | | an Active Record object | a plain Hash of attributes, not a model | Top-level keys are stringified by the session object, so symbol and string access both work there. Nested hashes are not converted back, which is the classic surprise. ## Why "store an id, not an object" - **Size.** Four kilobytes after encryption and Base64 encoding leaves room for a few ids and short strings, not a basket with line items. - **Staleness.** A copied record would be out of date as soon as the database row changed. - **Exposure.** The customer cannot read the cookie, but the customer **holds** it: a copy taken from the browser can be replayed until it stops decrypting or expires. Keep the basket in a table and its id in the session; the controller loads it with `Basket.find_by(id: session[:basket_id])` and starts a new one when that returns `nil`. ## The cookie's own attributes The options passed to `config.session_store` also shape the cookie itself: - **`key:`** renames it from `_bakery_session`. - **`expire_after:`** gives it an expiry; without it the cookie lasts until the browser session ends. - **`same_site:`** defaults to `config.action_dispatch.cookies_same_site_protection`, which is `:lax` under the 6.1 defaults and later. - **`domain:`** shares it across subdomains, for example `domain: ".bakery.example"`. - **`secure:`** restricts it to HTTPS; the cookie is `HttpOnly` by default, so page scripts cannot read it. ## Reading, deleting and turning it off - `session[:basket_id]` reads, `session.delete(:basket_id)` removes one key, `reset_session` clears everything and issues a new session id. - The session is also available in views and helpers. - `config.session_store :disabled` tells Rails not to manage a session at all; API-only apps leave the session middleware out. ## Common wrong answers - **"In the database"**: only with a server-side store or a store gem; the default holds no server record. - **"In memory on the server"**: nothing is kept between requests in the process. - **"In a signed but readable cookie"**: the session cookie goes through the encrypted jar, so the contents are not readable without `secret_key_base`.
- Why does session[:pickup][:slot] return nil on the request after you stored { slot: "9am" }?The session is serialized to JSON, so the nested hash comes back with string keys: `{ "slot" => "9am" }`. The session object stringifies only top-level keys on access. Read it with `session[:pickup]["slot"]`, or store flat values such as `session[:pickup_slot]`.
- What happens to every user's session if secret_key_base changes?The encrypted session cookies no longer decrypt, so every session reads as empty and users lose their baskets and sign-ins. Rails can accept the old secret while writing with the new one through `config.action_dispatch.cookies_rotations`, which re-encrypts cookies as they arrive.
- the default Rails session store keeps the data in the server's memory
- the session cookie is only signed, so the customer can read its contents
- storing the whole Basket record in session is fine because it is encrypted
- nested hashes in session come back with the symbol keys they were stored with
- a session cookie that fails to decrypt raises an error on every request
Assumes Rails 8.1 with load_defaults 8.1, which includes the :json cookie serializer (7.0 defaults) and AES-256-GCM cookie encryption (5.2 defaults).