Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Routing and Controllers

Sessions, Cookies and Flash

Learn how HTTP stays stateless, and how Rails uses cookies, the encrypted session and the flash to remember users and show one-time messages. Includes runnable stand-ins for each mechanism.

HTTP has no memory. Every request is independent, so the server does not know that the person who just logged in is the same person asking for the next page. Web apps solve this with cookies: tiny pieces of text the browser stores and sends back with each request. Rails builds three conveniences on top: cookies (raw values), session (a per-visitor hash) and flash (messages that last for exactly one more request).

In this lesson you will use all three, learn how the session is protected from tampering, and see why a cookie store with 4 KB of space shapes what you may keep in it. Real Rails code is read-only on this page; the stand-ins model the mechanisms with plain Ruby so you can run them.

Cookies

A cookie is a name and a value the server asks the browser to keep. In a controller:

Ruby
# read-only
cookies[:theme] = "dark"                              # simple cookie, session length
cookies[:theme] = { value: "dark", expires: 1.year }  # with options
cookies.permanent[:locale] = "en"                     # 20 years
cookies.signed[:user_id] = 42                         # tamper-proof, readable
cookies.encrypted[:token] = "secret"                  # tamper-proof and unreadable
cookies.delete(:theme)

Plain cookies can be read and edited by the user. Signed cookies carry a signature so the server can detect changes, and encrypted cookies are also unreadable. Both use the app's secret key.

Useful options: httponly: true hides the cookie from JavaScript (blocks theft by cross-site scripting), secure: true sends it only over HTTPS, and same_site: :lax limits it on cross-site requests. Rails sets safe values for its own session cookie.

The session

session looks like a Hash that lasts for the visitor's browsing. Behind the scenes Rails stores the whole hash encrypted inside one cookie by default (the cookie store), so there is nothing in your database.

Ruby
# read-only
session[:user_id] = user.id          # log in
session[:cart] ||= []                # shopping cart ids
User.find_by(id: session[:user_id])  # who is this?
session.delete(:user_id)             # log out
reset_session                        # clear everything (do this on login and logout)

Rules of thumb:

  • Keep small values (ids, flags). The cookie limit is about 4 KB. Store records in the database and the id in the session.
  • Never store secrets or sensitive personal data. Encrypted does not mean you want it travelling with every request.
  • Call reset_session when a user logs in, to prevent session fixation (an attacker planting a known session id). Authentication is covered later, in the Authentication and Security chapter.
  • You can switch the store to the database or Redis for large sessions (config/initializers/session_store.rb).

Cookies, session, flash

cookies Raw values, one per name.
session A hash kept across requests.
flash Shown once, then gone.
1 / 2

Stand-in: signed values

Here is how a signed cookie works, using the standard openssl library for an HMAC signature. The value is readable; only the signature stops edits.

Ruby Stand-in: signing and verifying a cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The forged cookie fails verification because the signature belongs to the old value. Rails does the same, plus encryption for the session cookie.

Flash: messages for the next request

After you create or delete something, you redirect and want to show "Article saved". The new request is a fresh one, so ordinary instance variables are gone. The flash carries a message across exactly one redirect.

Ruby
# read-only: in the controller
redirect_to @article, notice: "Article saved."       # flash[:notice]
redirect_to root_path, alert: "Please sign in."      # flash[:alert]
flash[:success] = "Welcome back!"                     # any key
flash.now[:alert] = "Fix the errors"                  # for THIS request (render)
ERB
<%# read-only: in the layout %>
<% flash.each do |type, message| %>
  <div class="flash <%= type %>"><%= message %></div>
<% end %>

Use redirect_to ..., notice: after a redirect and flash.now when you render instead, because render does not start a new request and a plain flash would show the message twice: now and on the following page.

sequenceDiagram
  participant B as Browser
  participant S as Server
  B->>S: POST /articles
  S-->>B: 302 to /articles/7 (flash[:notice] set)
  B->>S: GET /articles/7
  Note right of S: flash shown, then swept
  S-->>B: page with notice
  B->>S: GET /articles
  S-->>B: page without notice

A flash value survives one redirect and is removed after the next request.

Stand-in: a session hash with flash sweeping

This stand-in models the session as a hash that is serialized between requests, with a flash that is swept. Each loop iteration plays one request.

Ruby Stand-in: session and flash across requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

create sets a flash and it appears on the next show only. The second show has no message. The invalid request uses flash.now, so it appears immediately and is never stored.

The cookie store is not a safe place for things the user must not see or change in meaning, such as a price. Even encrypted, a copy of an old cookie stays valid until it expires, so do not keep authorization data (like "is_admin") in the session. Keep the user's id and look up their permissions on each request.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a web app need cookies to remember a logged-in user?

    HTTP is stateless, so the browser sends a cookie back to link requests together.
  2. 2. What is the default place Rails stores session data?

    The cookie store keeps the whole session, encrypted, in one cookie.
  3. 3. When should you use flash.now instead of flash?

    flash.now shows for the current request only, which suits render. Plain flash survives one more request, so it suits redirect.
  4. 4. Which cookie option hides it from JavaScript?

    HttpOnly cookies cannot be read by scripts, which limits damage from cross-site scripting.

Summary

  • HTTP is stateless; cookies let the browser identify itself on each request.
  • cookies holds raw values (use signed or encrypted for sensitive ones); session is a hash stored encrypted in a cookie by default.
  • Keep session data small, store ids rather than records, and reset_session on login and logout.
  • flash carries a message across one redirect; use flash.now when rendering.
  • Never trust the session for facts that can change, such as roles.

Next: ERB Templates in Rails