In a Rails controller, which attributes does cookies[:banner_dismissed] get by default, and how do expires:, httponly:, secure:, same_site: and domain: change them?
answer
- path slash and SameSite by default
- no HttpOnly unless you ask
- expires: takes a Time or a Duration
- secure cookies skipped over plain HTTP
- delete with the same domain:
basics
~20 sBy default Rails sets path=/ and the SameSite value from cookies_same_site_protection (Lax under 6.1+ defaults), with no expiry, HttpOnly, Secure or Domain. expires: accepts a Time or Duration, httponly: and secure: add those flags, same_site: overrides SameSite, domain: widens scope.
solid answer
~40 s`cookies[:banner_dismissed] = "1"` produces a browser-session cookie with `path=/` and `SameSite` from `config.action_dispatch.cookies_same_site_protection`, `:lax` under the 6.1 defaults and later; Rails adds no `HttpOnly`, `Secure` or `Domain` unless you ask. Pass a hash to change that: `expires: 1.year` (a Duration becomes `from_now`) or a `Time`; `httponly: true`; `secure: true`, which Rails skips writing on a plain-HTTP request outside development; `same_site: :strict`, `:none` or `nil`; and `domain: :all`, an array of domains or a proc. `config.force_ssl` makes `ActionDispatch::SSL` flag every cookie secure. To delete, call `cookies.delete(:banner_dismissed)` with the same `domain:` and `path:` you set; it does nothing if the request did not send the cookie.
code
ruby · 11 linesclass BannersController < ApplicationController
def dismiss
cookies[:banner_dismissed] = { value: "1", expires: 1.year, domain: :all }
head :no_content
end
def restore
cookies.delete(:banner_dismissed, domain: :all)
head :no_content
end
endgo deeper
Recall the hash form with value: and expires:, that Rails adds path=/ and SameSite=Lax, and that HttpOnly and Secure must be requested.
Explain Duration versus Time for expires:, the secure write rule, domain: :all, arrays and procs, and why delete must repeat domain: and path:.
Show you set app-wide SameSite with cookies_same_site_protection, rely on force_ssl for Secure, and catch cookies missing in HTTP staging.
Define the team's cookie defaults once in configuration and review exceptions, so attribute choices are not re-decided in every controller.
## The defaults Rails applies Writing a cookie with just a value: ```ruby cookies[:banner_dismissed] = "1" ``` produces a `Set-Cookie` header with: - **`path=/`**, because Rails fills in `path: "/"` when you give none; - **`SameSite`** taken from `config.action_dispatch.cookies_same_site_protection`, which is **`:lax`** under `load_defaults` 6.1 and later; - **no `expires`**, so it is a browser-session cookie; - **no `HttpOnly`** and **no `Secure`**, both default to false in the cookie jar; - **no `Domain`**, so it is sent only to the exact host that set it. The value is sent as text; a non-String value is converted with `to_s`. ## The options you can pass Use a hash with `value:` to set attributes: ```ruby cookies[:banner_dismissed] = { value: "1", expires: 1.year, httponly: true, same_site: :lax } ``` | Option | Accepts | Effect | |---|---|---| | `expires:` | a `Time` or a Duration such as `1.year` | a Duration is turned into `from_now` | | `httponly:` | `true` / `false` | hides the cookie from page scripts | | `secure:` | `true` / `false` | HTTPS only; see the write rule below | | `same_site:` | `:lax`, `:strict`, `:none`, `nil` | overrides the app-wide setting for this cookie | | `domain:` | `:all`, a String, an Array, a proc | widens or picks the cookie's domain | | `path:` | a String | narrows where the cookie is sent | ## Details that trip people up 1. **`secure: true` over plain HTTP.** The jar does not write a secure cookie on a non-HTTPS request unless `always_write_cookie` is on (Rails turns it on in **development**) or the host ends in `.onion`. In a test or staging environment served over HTTP, the cookie is silently missing. 2. **`config.force_ssl = true`** inserts `ActionDispatch::SSL`, whose `secure_cookies` option (on by default) adds `Secure` to every cookie in the response. 3. **`domain: :all`** sets the cookie for the host's last two labels (three for names like `co.uk`), so `www.news.example` and `app.news.example` share it; `tld_length:` fixes two-letter domains such as `lvh.me`. An **Array** picks the first entry matching `request.host`; a **proc** decides per request. 4. **`cookies_same_site_protection`** accepts a symbol or a proc that receives the request, so an app can choose per user agent; an unknown value raises `ArgumentError` when the cookie is written. ## Where the jar is available `cookies` is a private controller method that returns `request.cookie_jar`; `ActionController::Cookies` also exposes it to views with `helper_method`, so a layout can check `cookies[:banner_dismissed]` directly. Reads return the cookies the browser sent **plus** any written earlier in the same request, so a value set in a `before_action` is visible to the action and the view without waiting for the next request. Nothing reaches the browser until the response's `Set-Cookie` headers are written at the end. ## Deleting a cookie `cookies.delete(:banner_dismissed)` sends an expired, empty cookie. Two Rails specifics: - It **returns `nil` and does nothing** if the current request did not carry that cookie. - The `domain:` and `path:` must match what was used when setting it; with `domain: :all` you must pass `domain: :all` again. `cookies.deleted?(:banner_dismissed)` reports whether the jar will delete it with the given options, which is handy in tests. ## A sensible set for a news reader - **Banner flag**: `value: "1", expires: 1.year`; no need for `httponly` since nothing secret is stored, though it does no harm. - **Remember-me token**: signed jar, `httponly: true`, `secure: true`, an explicit `expires:`. - **Cross-subdomain preference** shared by `www` and `app`: `domain: :all`, and the same option on delete.
- Why does a cookie set with secure: true never appear in a staging environment served over plain HTTP?Rails' cookie jar writes a secure cookie only when the request is HTTPS, the host ends in `.onion`, or `always_write_cookie` is true, which Rails enables only in development. Serve staging over HTTPS, or make sure Rails sees the proxy's HTTPS requests as HTTPS.
- How would you set SameSite=Strict for every cookie except one?Set `config.action_dispatch.cookies_same_site_protection = :strict`, which every cookie without its own `same_site:` uses, including the session cookie. For the exception pass `same_site: :lax` (or `:none` with `secure: true`) when writing that cookie.
- Rails marks every cookie HttpOnly unless you pass httponly: false
- expires: only accepts a Time, so 1.year must be converted by hand
- secure: true cookies are always written, whatever the request's scheme
- cookies.delete(:name) removes a cookie that was set with domain: :all
- a cookie with no same_site: option is sent with no SameSite attribute