Sub topic 16
Sessions and protected routes
This chapter shows how to remember a logged-in user across requests and keep signed-out visitors away from private pages. It assumes you know HTTP cookies and status codes, the loader and action exports from earlier chapters, and the .server.ts convention for server-only modules.
Why a session is needed
HTTP is stateless. Each request arrives with no memory of the previous one. A session fixes this by storing a small piece of state, such as a user ID, and tying it to the browser with a cookie.
React Router offers several session storage helpers. This chapter uses createCookieSessionStorage. It keeps the session data inside the cookie itself, so you need no database table for sessions. The cookie is signed with a secret, so the browser cannot change its contents without the server noticing.
Signed is not the same as encrypted. The browser can read the data in the cookie. Store an ID and small flags, and never store passwords or private details.
Creating session storage
Put the storage in a .server.ts file so the bundler keeps it out of the browser build.
// app/sessions.server.ts
import { createCookieSessionStorage } from "react-router";
export const { getSession, commitSession, destroySession } =
createCookieSessionStorage({
cookie: {
name: "__session",
httpOnly: true,
sameSite: "lax",
secrets: [process.env.SESSION_SECRET!],
secure: process.env.NODE_ENV === "production",
},
});Each option has a purpose:
| Option | Effect |
|---|---|
| `httpOnly` | Browser JavaScript cannot read the cookie, which limits damage from XSS. |
| `sameSite: "lax"` | The cookie is not sent on cross-site POST requests, which reduces CSRF risk. |
| `secrets` | Keys used to sign the cookie. The first key signs, and all keys can verify. |
| `secure` | The cookie is sent only over HTTPS. It is off in development so `http://localhost` works. |
To rotate secrets, put the new secret first and keep the old one in the array. Existing sessions stay valid until they expire.
The three helpers do the following:
getSession(cookieHeader)parses theCookieheader and returns a session object.commitSession(session)returns aSet-Cookieheader value.destroySession(session)returns aSet-Cookieheader value that clears the cookie.
The login flow
The action below verifies the form, stores the user ID in the session, and redirects. The redirect must carry the Set-Cookie header, or the browser never receives the session.
// app/routes/login.tsx
import { Form, data, redirect } from "react-router";
import type { Route } from "./+types/login";
import { getSession, commitSession } from "~/sessions.server";
import { verifyLogin } from "~/users.server";
export async function loader({ request }: Route.LoaderArgs) {
const session = await getSession(request.headers.get("Cookie"));
if (session.has("userId")) {
return redirect("/dashboard");
}
return data(
{ error: session.get("error") },
{ headers: { "Set-Cookie": await commitSession(session) } },
);
}
export async function action({ request }: Route.ActionArgs) {
const session = await getSession(request.headers.get("Cookie"));
const form = await request.formData();
const email = String(form.get("email") ?? "");
const password = String(form.get("password") ?? "");
const userId = await verifyLogin(email, password);
if (!userId) {
session.flash("error", "Invalid email or password");
return redirect("/login", {
headers: { "Set-Cookie": await commitSession(session) },
});
}
session.set("userId", userId);
return redirect("/dashboard", {
headers: { "Set-Cookie": await commitSession(session) },
});
}
export default function Login({ loaderData }: Route.ComponentProps) {
return (
<Form method="post">
{loaderData.error ? <p role="alert">{loaderData.error}</p> : null}
<input name="email" type="email" autoComplete="username" />
<input name="password" type="password" autoComplete="current-password" />
<button type="submit">Log in</button>
</Form>
);
}session.flash stores a value that is removed after the next read. That makes it suited to one-time messages. The loader must commit the session after reading it, because reading a flash value changes the session and the cookie must be rewritten to remove it.
Protecting routes
Do the check in a loader, not in the component. A loader runs on the server before any HTML is sent, so an unauthenticated user never receives private data. A check in the component would run after the data had already been sent.
Put the logic in one helper so every route uses the same rule.
// app/auth.server.ts
import { redirect } from "react-router";
import { getSession } from "~/sessions.server";
export async function requireUserId(request: Request): Promise<string> {
const session = await getSession(request.headers.get("Cookie"));
const userId = session.get("userId");
if (!userId) {
const url = new URL(request.url);
const next = encodeURIComponent(url.pathname + url.search);
throw redirect(`/login?next=${next}`);
}
return userId;
}The helper throws the redirect, so the calling loader stops at that line. Use it like this:
// app/routes/dashboard.tsx
import type { Route } from "./+types/dashboard";
import { requireUserId } from "~/auth.server";
import { getProjectsFor } from "~/projects.server";
export async function loader({ request }: Route.LoaderArgs) {
const userId = await requireUserId(request);
return { projects: await getProjectsFor(userId) };
}
export default function Dashboard({ loaderData }: Route.ComponentProps) {
return (
<ul>
{loaderData.projects.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
);
}Common mistakes
- Protecting only the layout loader. Loaders for sibling and child routes run in parallel on a client-side navigation, and they can be requested on their own as data requests. A layout's check does not stop a child loader from running. Call
requireUserIdin every loader and action that touches private data. - Forgetting actions. A POST to an action URL can be sent without ever loading the page. Guard each action as well.
- Dropping the cookie header. If you
redirectaftersession.setwithoutheaders, the user is not logged in. - Trusting
next. If you redirect to anextparameter after login, accept only paths that start with a single/. Otherwise an attacker can send users to another site. - Missing
SESSION_SECRET. The non-null assertion!hides an undefined value, and signing with it fails at runtime. Check for it at startup.
Logging out
Logout changes state, so use a POST action rather than a link. A GET link can be triggered by an image tag on another site.
// app/routes/logout.tsx
import { redirect } from "react-router";
import type { Route } from "./+types/logout";
import { getSession, destroySession } from "~/sessions.server";
export async function action({ request }: Route.ActionArgs) {
const session = await getSession(request.headers.get("Cookie"));
return redirect("/login", {
headers: { "Set-Cookie": await destroySession(session) },
});
}Render a <Form method="post" action="/logout"> with a button to call it.
Cookie storage limits
Browsers cap a cookie at about 4 KB. With cookie storage, all session data counts against that limit. If you need more space, or want to revoke a session on the server, use createSessionStorage or a database-backed store that keeps data on the server and puts only a session ID in the cookie. The getSession, commitSession, and destroySession helpers keep the same shape, so the routes in this chapter do not change.
Exercise
A layout route's loader calls requireUserId. A child route /dashboard/settings has a loader that returns the user's email address, with no auth check of its own. Why is this unsafe, and what is the fix?
Show answer
Loaders for matched routes run in parallel and can be requested individually, so the layout's check does not prevent the child loader from running or returning data. The fix is to call requireUserId inside the child loader (and in any child actions) so each one enforces authentication itself.
Exercise
After session.set("userId", userId), the action returns redirect("/dashboard") with no headers. What happens, and how do you fix it?
Show answer
The change exists only in memory on the server and is lost, so the browser receives no session cookie and is not logged in. Pass headers: { "Set-Cookie": await commitSession(session) } to redirect.