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

  1. 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.
  2. Loaders: check the session in the loader and throw redirect before rendering. No flash of protected content.
  3. 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.
  4. Frameworks: Next.js uses proxy.ts for optimistic redirects plus checks in Server Components and Server Functions.

Good UX

  • Remember where the user wanted to go (?next=/billing or location.state.from) and return there after login.
  • Use replace so 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";
2
3type User = { id: string; role: "user" | "admin" };
4export const userContext = createContext<User | null>(null);
5
6async function getSessionUser(): Promise<User | null> {
7 const res = await fetch("/api/me", { credentials: "include" });
8 return res.ok ? res.json() : null;
9}
10
11// Data mode middleware (v8): runs before child loaders
12const 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};
21
22export 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.

Open in study app