Sub topic 14
Protecting routes
This chapter assumes you can define routes with createBrowserRouter, nest them under a layout with Outlet, and write a loader. Here you will use loaders to send unauthenticated users to a login page before a protected page renders.
Why a loader is the right place
A common first attempt is a component that checks for a user and renders <Navigate to="/login" />. That works, but the protected component has already started rendering, so you can get a flash of protected content. A loader runs before the route renders. If it throws a redirect, the router goes to the new location and the protected element never mounts.
Guarding a single route
import { redirect } from "react-router-dom";
export function requireAuth({ request }) {
if (!localStorage.getItem("token")) {
const url = new URL(request.url);
const from = encodeURIComponent(url.pathname + url.search);
throw redirect(`/login?from=${from}`);
}
return null;
}
// Route definition:
// { path: "dashboard", element: <Dashboard />, loader: requireAuth }A loader must return a value or null, so the success path returns null. The loader receives a request object. Its URL lets you remember where the user was going, so the login page can send them back after sign-in.
Guarding a group of routes
Repeating loader: requireAuth on every route is easy to forget. Put the guard on a pathless layout route instead. A pathless route has no path, so it adds no URL segment. It only wraps its children.
import { createBrowserRouter, Outlet } from "react-router-dom";
import { requireAuth } from "./requireAuth";
const router = createBrowserRouter([
{ path: "/login", element: <Login /> },
{
loader: requireAuth,
element: <Outlet />,
children: [
{ path: "dashboard", element: <Dashboard /> },
{ path: "settings", element: <Settings /> },
],
},
]);Any route added under this parent is protected by default.
Common errors
- Assuming the parent loader blocks child loaders. Loaders for matched routes run in parallel. If the parent redirects, the child's result is discarded, but the child's
fetchmay already have been sent. Your API must reject unauthenticated requests itself. - Treating the client check as security. Anyone can set a value in
localStorageor read your JavaScript bundle. The redirect is a user-experience feature. Real protection happens on the server, which should return401for missing or invalid credentials. - Returning
redirectfrom a component.redirectis for loaders and actions. In components, use<Navigate>oruseNavigate. - Forgetting the login route itself. If the guard also covers
/login, the redirect loops. Keep/loginoutside the guarded group, as above.
Exercise
You put loader: requireAuth on a parent layout route, and a child route has its own loader that calls /api/reports. An unauthenticated user visits the child URL. Is the user redirected, and can the /api/reports request still be sent?
Show answer
The user is redirected to the login page, because the parent loader throws a redirect. The child loader may still run in parallel, so the /api/reports request can still be sent. The server must reject it with a 401, or the child loader should call requireAuth itself.