Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Sessions and Authentication

Session Storage Options

Compare cookie, in-memory, file and database-backed session storage in Remix and React Router, build a custom createSessionStorage, and expire and rotate sessions.

The previous lesson used createCookieSessionStorage, where the whole session lives inside the cookie. That is easy and needs no database, but it is not the only choice. Remix and React Router offer a general function, createSessionStorage, where the cookie carries only a random session ID and your own code saves the data somewhere else: memory, a file, Redis or a SQL table. This lesson helps you choose, shows the API, and builds a runnable store so you can see what a "create, read, update, delete" session backend does.

The options compared

Storage Data lives in Good for Watch out for
Cookie (createCookieSessionStorage) the browser cookie, signed small apps, user ID plus flash 4 KB limit, cannot revoke a single session
Memory (createMemorySessionStorage) server RAM development and tests lost on restart, not shared between servers
Database / Redis (createSessionStorage) your datastore production with many users one extra read per request
File disk single small server slow, not shared

A server-side store has a major security advantage: you can revoke a session by deleting its row (for example "sign out everywhere" or after a password change). With a cookie-only session, a stolen cookie stays valid until it expires, because the server has nothing to delete.

The createSessionStorage contract

You provide four functions. React Router handles cookies and signing; you only persist data:

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

const sessionCookie = createCookie("__sid", {
  httpOnly: true,
  sameSite: "lax",
  secure: process.env.NODE_ENV === "production",
  secrets: [process.env.SESSION_SECRET!],
  maxAge: 60 * 60 * 24 * 7,
});

export const { getSession, commitSession, destroySession } = createSessionStorage({
  cookie: sessionCookie,

  async createData(data, expires) {
    const row = await db.session.create({ data: { json: JSON.stringify(data), expires } });
    return row.id; // this ID goes into the cookie
  },
  async readData(id) {
    const row = await db.session.findUnique({ where: { id } });
    if (!row || (row.expires && row.expires < new Date())) return null;
    return JSON.parse(row.json);
  },
  async updateData(id, data, expires) {
    await db.session.update({ where: { id }, data: { json: JSON.stringify(data), expires } });
  },
  async deleteData(id) {
    await db.session.deleteMany({ where: { id } });
  },
});

The route code that uses getSession, session.set, commitSession and destroySession does not change at all. You can start with a cookie session and move to a database later by swapping this one file, which is why session access should live in a single module.

Session IDs must be unguessable

The ID is the key to the account. Generate it from a cryptographic random source and make it long: at least 128 bits. crypto.randomUUID() or crypto.randomBytes(32) are fine, and Math.random() is not.

Node.js Stand-in: a session store with expiry and revocation

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.

Expiry: absolute, idle and rolling

  • Absolute expiry ends the session a fixed time after login (for example 30 days) no matter what.
  • Idle timeout ends it after a period of inactivity (for example 30 minutes for a banking app).
  • Rolling sessions push the expiry forward on each request. In this framework that happens whenever you commitSession with a fresh expires, so only commit when you actually want to extend.

Delete expired rows in a scheduled job, because a lookup that ignores expired rows still leaves them in the table.

Rotating the ID on login

Never keep the same session ID across the boundary between anonymous and signed-in. If an attacker plants a known ID in a victim's browser before login (session fixation), the old ID would become an authenticated session. The cure is cheap: on login, destroy the old session and create a new one with a fresh ID. Login and Logout does exactly this.

Node.js Stand-in: why rotation defeats fixation

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.

Which should you choose?

Start with the cookie session for a prototype or a small site where one user ID is enough. Move to a database-backed store when you need to revoke sessions, hold bigger data (a shopping cart) or run several servers. Whatever you pick, keep the code behind the three functions getSession, commitSession and destroySession so the rest of the app never knows the difference.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of a database-backed session over a cookie session?

    With the data on the server you can delete a session at any time. A cookie-only session stays valid until it expires.
  2. 2. What does the cookie contain when you use createSessionStorage?

    The cookie carries only the ID; createData, readData, updateData and deleteData persist the real data.
  3. 3. Why use createMemorySessionStorage only in development?

    Memory lives in one process, so deploys and multiple servers lose or split sessions.
  4. 4. How does rotating the session ID at login help?

    After rotation the planted ID no longer maps to an authenticated session.

Summary

  • Pick cookie, memory or custom storage; all expose getSession, commitSession, destroySession.
  • createSessionStorage needs four functions: create, read, update, delete.
  • IDs must be long and random; expire sessions and clean up old rows.
  • Rotate the ID on login and revoke by deleting rows (for example after a password change).
  • Keep all session code in one .server module.

Next: Login and Logout