Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Sessions and Authentication

Cookies and Sessions

Understand HTTP cookies, signing, createCookie and createCookieSessionStorage in Remix and React Router, flash messages, and how a session survives between requests.

HTTP is stateless: every request arrives with no memory of the previous one. A cookie is the browser's way to give the server that memory. The server sends a Set-Cookie header, the browser stores the value and returns it in a Cookie header on later requests to the same site. A session is the server-side idea built on top: a small bag of data (who is signed in, a flash message) that belongs to one visitor and is found again through a cookie.

Remix and React Router framework mode ship small helpers for both, because their loaders and actions work with plain Request and Response objects and have no hidden global state. This lesson shows the helpers (read-only, since the real server is not available here) and builds a runnable stand-in of a signed cookie so you see exactly what signing protects against.

A cookie is a name, a value and attributes:

HTTP
Set-Cookie: __session=eyJ1c2VySWQiOiIxIn0.x9s3...; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=604800
Attribute Effect
HttpOnly JavaScript in the page cannot read it, which limits damage from XSS
Secure only sent over HTTPS
SameSite=Lax not sent on cross-site POSTs, a first line of defense against CSRF
Max-Age / Expires how long it lives; without them it is a session cookie that ends when the browser closes
Path / Domain where it is sent

createCookie

createCookie builds a reusable description of one cookie with its attributes and a signing secret:

TypeScript
// app/cookies.server.ts (React Router framework mode, read-only)
import { createCookie } from "react-router";

export const prefs = createCookie("prefs", {
  maxAge: 60 * 60 * 24 * 365, // one year
  httpOnly: true,
  sameSite: "lax",
  secure: process.env.NODE_ENV === "production",
  secrets: [process.env.COOKIE_SECRET!],
});

Use it in a loader to read, and in an action to write:

TypeScript
export async function loader({ request }: Route.LoaderArgs) {
  const cookie = (await prefs.parse(request.headers.get("Cookie"))) ?? {};
  return { theme: cookie.theme ?? "light" };
}

export async function action({ request }: Route.ActionArgs) {
  const form = await request.formData();
  return data(null, {
    headers: { "Set-Cookie": await prefs.serialize({ theme: form.get("theme") }) },
  });
}

secrets is a list: the first signs new cookies, the rest still verify old ones, so you can rotate a secret without logging everyone out. Files ending in .server.ts never reach the browser bundle, which is where your secret must live.

Signing: why it matters

A cookie sits on the visitor's machine, so they can edit it. If the cookie held {"admin":true} as plain text, anyone could grant themselves admin rights. A signed cookie appends a keyed hash (an HMAC) of the value; the server recomputes it on every request and rejects the cookie if the two differ. Signing does not hide the data (it is still readable), it only prevents tampering.

Node.js Stand-in: sign and verify a cookie value

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 node:readline or process.stdin), it gets the next line from this box.

Sessions with createCookieSessionStorage

A session storage object hands out Session objects with get, set, has, unset and flash. The simplest storage keeps all the session data inside the signed cookie itself:

TypeScript
// app/sessions.server.ts (read-only)
import { createCookieSessionStorage } from "react-router";

type SessionData = { userId: string };
type SessionFlash = { error: string; success: string };

export const { getSession, commitSession, destroySession } =
  createCookieSessionStorage<SessionData, SessionFlash>({
    cookie: {
      name: "__session",
      httpOnly: true,
      maxAge: 60 * 60 * 24 * 7,
      sameSite: "lax",
      secrets: [process.env.SESSION_SECRET!],
      secure: process.env.NODE_ENV === "production",
    },
  });

The three functions form the whole workflow:

  1. getSession(request.headers.get("Cookie")) reads the cookie and returns a Session.
  2. You call session.set("userId", "42").
  3. commitSession(session) returns the Set-Cookie string, which you put on the response. Nothing is saved until you commit and send that header. This is the most common bug: forgetting the header.

Flash messages

session.flash("success", "Saved!") stores a value that disappears after it is read once. It is perfect for the "post, redirect, show a message" pattern:

TypeScript
export async function action({ request }: Route.ActionArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  session.flash("success", "Profile saved");
  return redirect("/profile", { headers: { "Set-Cookie": await commitSession(session) } });
}

export async function loader({ request }: Route.LoaderArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  const success = session.get("success") ?? null;
  // reading a flash value removes it, so the cookie must be committed again
  return data({ success }, { headers: { "Set-Cookie": await commitSession(session) } });
}
Node.js Stand-in: a session with flash values

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 node:readline or process.stdin), it gets the next line from this box.

Limits to know

A browser keeps about 4 KB per cookie, so cookie sessions suit a user ID and a few flags. For bigger data use a database-backed session, covered in Session Storage Options. Never put secrets (a password, a card number) into a cookie session: signed is not encrypted.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does signing a cookie protect against?

    A signature lets the server detect tampering. The content is still readable, so never store secrets in it.
  2. 2. You call session.set(...) in an action but the user stays signed out. What is the likely bug?

    Session changes only persist when the committed cookie is returned on the response.
  3. 3. Why does secrets accept an array?

    Old secrets keep verifying existing cookies while new cookies are signed with the newest one.
  4. 4. What does a flash value do?

    Flash data is removed after being read, ideal for one-time messages after a redirect.
  5. 5. Which cookie attribute stops page JavaScript from reading the cookie?

    HttpOnly hides the cookie from document.cookie, which limits what an XSS attack can steal.

Summary

  • Cookies give stateless HTTP a memory; a session is per-visitor data found through a cookie.
  • createCookie and createCookieSessionStorage live in .server files and need a secret.
  • Signing prevents tampering but does not hide content; rotate secrets via the secrets array.
  • Always return commitSession(session) in Set-Cookie; reading a flash needs a commit too.
  • Cookie sessions are small (about 4 KB).

Next: Session Storage Options