Sub topic 16
Sessions and protected routes
This chapter assumes you can write a loader and an action, and that you know how cookies and Set-Cookie headers work. It covers cookie-based sessions with route protection, then streaming slow data with Await.
Cookie sessions
A session stores per-user data between requests. React Router's createCookieSessionStorage keeps that data inside a signed cookie, so you don't need a database. Put the storage in a .server.ts file so it never reaches the browser bundle.
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",
},
});httpOnlyhides the cookie from client JavaScript.secretssigns the cookie. A tampered cookie is rejected. Signing does not encrypt, so don't store sensitive values in the session.- Cookies are limited to about 4 KB. Store a user ID, not a whole user object.
Logging in and protecting routes
The login action writes to the session and sends the updated cookie back in a Set-Cookie header on the redirect.
import { redirect } from "react-router";
import type { Route } from "./+types/login";
import { getSession, commitSession } from "~/sessions.server";
import { verifyLogin } from "~/users.server";
export async function action({ request }: Route.ActionArgs) {
const session = await getSession(request.headers.get("Cookie"));
const form = await request.formData();
const userId = await verifyLogin(
String(form.get("email")),
String(form.get("password")),
);
if (!userId) {
return { error: "Invalid email or password" };
}
session.set("userId", userId);
return redirect("/dashboard", {
headers: { "Set-Cookie": await commitSession(session) },
});
}A protected route checks the session in its loader and redirects if the user is not signed in.
import { redirect } from "react-router";
import type { Route } from "./+types/dashboard";
import { getSession } from "~/sessions.server";
export async function loader({ request }: Route.LoaderArgs) {
const session = await getSession(request.headers.get("Cookie"));
if (!session.has("userId")) {
throw redirect("/login");
}
return { userId: session.get("userId") };
}To log out, call destroySession(session) in an action and send the result as Set-Cookie.
Streaming slow data with Await
A loader normally blocks the page until everything it awaits has resolved. If one query is slow, you can return its promise without awaiting it. The page renders immediately, and the slow value streams in later.
import { Suspense } from "react";
import { Await } from "react-router";
import type { Route } from "./+types/stats";
import { getUser, getStats } from "~/stats.server";
export async function loader() {
const user = await getUser();
const stats = getStats();
return { user, stats };
}
export default function Stats({ loaderData }: Route.ComponentProps) {
return (
<section>
<h1>{loaderData.user.name}</h1>
<Suspense fallback={<p>Loading stats...</p>}>
<Await
resolve={loaderData.stats}
errorElement={<p>Could not load stats</p>}
>
{(stats) => <p>{stats.visits} visits</p>}
</Await>
</Suspense>
</section>
);
}awaitthe data that the page can't render without. Leave the rest as promises.Suspenseshows the fallback until the promise resolves.errorElementhandles a rejected promise locally, so the rest of the page still renders.
Exercise
Why must a protected loader throw the redirect, and what happens if you don't check the session in a child route because its layout already did?
Show answer
Throwing the redirect stops the loader so no protected data is returned. Loaders for a layout and its children run in parallel, so a layout check doesn't stop the child loader from running. Each protected loader and action must check the session itself.