Skip to the workspace
Pebellslearn by building
Controllers  ›  Capstone Project

Cookies, Sessions and Flash

Sessions 15 minHTTP forgets each request, so Rails stores small facts in cookies; the session is a signed, encrypted cookie for things like the signed-in member's id, and flash lasts exactly one more request.

ruby on rails / Cookies, Sessions and Flash

Explore each scene at your own pace.

01 · The rule

The rule

Cookies, Sessions and Flash

HTTP has no memory. Each request arrives alone, with nothing to say that the same member signed in a minute ago. To remember anything between requests, the server asks the browser to carry a small note and send it back every time. That note is a cookie, and Rails gives you three tools built on it.

The rule

Cookies carry notes; the session keeps secrets; flash lasts one hop.

Cookies are small name-value pairs the browser stores and sends back:

cookies[:theme] = "dark"                          # until the browser closes
cookies.permanent[:theme] = "dark"                # about 20 years
cookies.signed[:last_book_id] = @book.id          # readable, but tamper-proof
cookies.encrypted[:hint] = "secret"               # unreadable and tamper-proof
cookies.delete(:theme)

A plain cookie can be read and changed by the user, so never trust it for anything important.

The session is a hash that Rails stores in one signed and encrypted cookie by default. The user cannot read it or change it:

session[:member_id] = member.id          # on sign-in
Member.find_by(id: session[:member_id])  # on every later request
reset_session                            # on sign-out

Because the session lives in a cookie, it has a size limit of about 4 KB. Store small ids, not whole objects.

The flash is a special part of the session that survives exactly one more request — made for messages after a redirect:

redirect_to @book, notice: "Review posted."     # sets flash[:notice]
flash.now[:alert] = "Rating is missing."        # for a render in this request
<p class="notice"><%= notice %></p>

Rails 8's bin/rails generate authentication builds sign-in for you, using a signed cookie that points at a sessions table, so the same idea holds: store a small id, look up the rest.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.