Sub topic 14
Protecting routes
This chapter assumes you can define routes with createBrowserRouter, write loaders and actions, and use redirect. A protected route is a page that only signed-in users can see. Everyone else is sent to a login page. The chapter shows how to build that guard in the data router API, how to send users back to the page they wanted, and where the guard stops being reliable.
Why guard in a loader
You can protect a page in two places:
- In the component, after it renders. The component checks auth state and renders
<Navigate to="/login" />. - In a loader, before the route renders. The loader throws
redirect("/login").
The loader approach is usually better. The protected component never renders for an anonymous user, so nothing flashes on screen. The check also runs on every navigation to the route, so there is no gap between "the URL changed" and "the guard ran".
| Approach | Runs | Flash of protected UI | Best for |
|---|---|---|---|
| Throw `redirect` in a loader | Before render | No | Most apps using a data router |
| Render `<Navigate>` in a wrapper component | During render | Possible if the wrapper renders children first | Auth state that lives only in React context |
| Check inside each page component | During render | Possible | Avoid. The check gets duplicated and forgotten |
The basic guard
A loader that throws a Response stops the navigation. React Router follows the redirect instead of rendering the route. The helper below also records where the user was going, so they can return after logging in.
import { redirect } from "react-router-dom";
export function getToken() {
return localStorage.getItem("token");
}
export function requireAuth(request) {
if (!getToken()) {
const url = new URL(request.url);
const from = url.pathname + url.search;
throw redirect(`/login?from=${encodeURIComponent(from)}`);
}
}Loaders receive a request object whose url is the destination being navigated to. This is why requireAuth takes request. The user's intended path is available even though the browser location has not changed yet.
Guarding many routes at once
Repeating requireAuth on every route is easy to forget. Put the check on a parent layout route instead. A layout route with no path (a pathless route) adds no URL segment. It only wraps its children.
import { createBrowserRouter, Outlet, Link } from "react-router-dom";
import { requireAuth } from "./auth";
function ProtectedLayout() {
return (
<div>
<nav>
<Link to="/dashboard">Dashboard</Link> <Link to="/settings">Settings</Link>
</nav>
<Outlet />
</div>
);
}
export const router = createBrowserRouter([
{ path: "/login", element: <Login />, action: loginAction },
{
element: <ProtectedLayout />,
loader: ({ request }) => {
requireAuth(request);
return null;
},
children: [
{ path: "dashboard", element: <Dashboard />, loader: dashboardLoader },
{ path: "settings", element: <Settings /> },
],
},
]);A loader must return a value. Returning null is the convention for "no data, just a check".
Child loaders still need their own check
Loaders for nested routes run in parallel, not one after another. When the parent loader redirects, dashboardLoader may already have started. React Router aborts the request signal, but your code may have sent a fetch before then. Two rules follow:
- Do not assume a child loader runs only after the parent's check passed.
- Make the API reject unauthenticated requests. The loader should treat a
401as a reason to redirect.
import { redirect } from "react-router-dom";
import { getToken } from "./auth";
export async function dashboardLoader({ request }) {
const res = await fetch("/api/dashboard", {
headers: { Authorization: `Bearer ${getToken()}` },
signal: request.signal,
});
if (res.status === 401) {
localStorage.removeItem("token");
throw redirect("/login");
}
if (!res.ok) {
throw new Response("Could not load dashboard", { status: res.status });
}
return res.json();
}Passing request.signal to fetch cancels the request when the navigation is interrupted. Handling 401 also covers expired tokens, which a simple "is there a token" check cannot detect.
Returning the user to where they were going
The from query parameter set by requireAuth is read by the login action. After a successful login, the action redirects to that path.
import { Form, redirect, useActionData, useNavigation } from "react-router-dom";
function safeTarget(from) {
// Only allow same-site paths such as "/dashboard?tab=1".
if (from && from.startsWith("/") && !from.startsWith("//")) {
return from;
}
return "/dashboard";
}
export async function loginAction({ request }) {
const formData = await request.formData();
const res = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: formData.get("email"),
password: formData.get("password"),
}),
});
if (!res.ok) {
return { error: "Invalid email or password" };
}
const { token } = await res.json();
localStorage.setItem("token", token);
const from = new URL(request.url).searchParams.get("from");
return redirect(safeTarget(from));
}
export function Login() {
const data = useActionData();
const navigation = useNavigation();
const busy = navigation.state === "submitting";
return (
<Form method="post">
{data?.error && <p role="alert">{data.error}</p>}
<input name="email" type="email" required />
<input name="password" type="password" required />
<button type="submit" disabled={busy}>{busy ? "Signing in..." : "Sign in"}</button>
</Form>
);
}A Form without an action prop posts to the current URL and keeps its query string, so from is available in the action. Failed logins return data instead of throwing. The component reads it with useActionData and shows the message on the same page.
The safeTarget function matters. Without it, a link like /login?from=https://evil.example would send a freshly logged-in user to another site. This is called an open redirect. Accepting only paths that start with a single / blocks it.
The whole flow looks like this:
Logging out and the reverse guard
Logging out is a mutation, so use an action. Clear the token, then redirect.
import { redirect } from "react-router-dom";
export async function logoutAction() {
localStorage.removeItem("token");
return redirect("/login");
}
// Route definition: { path: "logout", action: logoutAction }
// Trigger it with: <Form method="post" action="/logout"><button>Log out</button></Form>You can also guard in the opposite direction. A login loader can redirect users who already have a token to /dashboard. This keeps signed-in users from seeing a form they do not need.
Common errors
- Forgetting to return from the loader. A loader that returns
undefinedthrows an error. Returnnull. - Using
return redirect(...)inside a helper. The helper's return value is ignored by the caller. Usethrow redirect(...)in helpers so the redirect propagates, asrequireAuthdoes. - Guarding only the parent. Child routes can be loaded in parallel, so protect the data at the API as well.
- Putting
errorElementbelow the guard only. If the guard throws a non-redirect error, it needs anerrorElementon the layout route or above it. - Reading auth state from React context in a loader. Loaders run outside the component tree and cannot call hooks. Read from storage or from a module-level auth object.
Exercise
Exercise
A signed-out user opens /settings?tab=billing. Your guard throws redirect to /login?from=/settings. After login the user lands on /settings and the tab=billing part is lost. What is wrong in requireAuth, and how do you fix it?
Show answer
The helper built from from url.pathname alone, so the query string was dropped. Use url.pathname + url.search and wrap it in encodeURIComponent, so the characters ? and = survive as part of the single from value. The login action then reads from, passes it through safeTarget, and redirects to /settings?tab=billing.
Exercise
Why should dashboardLoader handle a 401 response even though the parent layout loader already checks for a token?
Show answer
The parent check only tests that a token exists. It cannot tell whether the token is expired or revoked, and child loaders run in parallel with the parent. The API's 401 response is the reliable signal, so the child loader clears the token and throws a redirect to /login.