ReactMedium
What are protected routes?
Protected routes are routes only available to users who meet a condition, usually being signed in or having a certain role. In React Router you protect them by checking auth before rendering: with middleware or a loader that throws redirect("/login") (data and framework modes), or with a guard layout component that renders <Navigate> or an <Outlet /> (declarative mode). The server must still enforce authorization for the data.
Approaches
- Middleware (React Router v8, stable): an auth middleware on a parent route checks the session and throws
redirect("/login"). It runs before loaders of all child routes. - Loaders: check the session in the loader and throw
redirectbefore rendering. No flash of protected content. - Guard component:
function RequireAuth() { return user ? <Outlet /> : <Navigate to="/login" replace state={{ from: location }} /> }. Simple, but data may already be requested by children and there can be a flash while auth loads. - Frameworks: Next.js uses
proxy.tsfor optimistic redirects plus checks in Server Components and Server Functions.
Good UX
- Remember where the user wanted to go (
?next=/billingorlocation.state.from) and return there after login. - Use
replaceso Back does not loop to the protected page. - Show a loading state while the session is being checked.
- Role-based checks render a "403 / no access" page instead of redirecting to login.
Security reminder
Client-side checks only control the UI. APIs must validate the session or token and permissions on every request; anyone can call your API directly.
Code example
tsx
1import { createBrowserRouter, createContext, redirect, Outlet, useLoaderData } from "react-router";23type User = { id: string; role: "user" | "admin" };4export const userContext = createContext<User | null>(null);56async function getSessionUser(): Promise<User | null> {7 const res = await fetch("/api/me", { credentials: "include" });8 return res.ok ? res.json() : null;9}1011// Data mode middleware (v8): runs before child loaders12const authMiddleware = async ({ request, context }: any, next: () => Promise<unknown>) => {13 const user = await getSessionUser();14 if (!user) {15 const from = new URL(request.url).pathname;16 throw redirect(`/login?next=${encodeURIComponent(from)}`);17 }18 context.set(userContext, user);19 return next();20};2122export const router = createBrowserRouter([23 { path: "/login", Component: () => <h1>Login</h1> },24 {25 path: "/app",26 middleware: [authMiddleware],27 loader: ({ context }) => context.get(userContext),28 Component: () => {29 const user = useLoaderData() as User;30 return <><p>Signed in as {user.id}</p><Outlet /></>;31 },32 children: [{ path: "reports", Component: () => <h1>Reports</h1> }],33 },34]);
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.