Full answer
Two questions are separate: who is the user (authentication) and what may they do (authorization). The browser can only decide what to show. Every API call must be checked again on the server, because anyone can edit client code.
Route protection. With React Router data routers, a loader on a parent route can check the session and throw redirect('/login'). This runs before the page renders, so there is no flash of protected content. A layout route can apply it to a whole group of routes. Without a data router, a RequireAuth component renders <Navigate to="/login" replace /> when there is no user. Remember the intended destination (a from parameter or state) to return after login. For role-based access, check roles in the same place and render a "forbidden" page for a missing permission, not the login page.
Session state. On load, ask the server who the user is (GET /me). Store the result in a provider or a query cache, and show a loading state until it resolves, so a refresh does not log the user out visually. Clear the cache on logout so another user does not see old data.
Token storage. Options: httpOnly cookies set by the server are not readable by scripts, so XSS cannot steal them, but they need CSRF defenses (SameSite=Lax or Strict, CSRF tokens for risky requests). Tokens in localStorage or sessionStorage are readable by any injected script. If an access token must be in memory (for an API on another domain), keep it short-lived in a variable, refresh through an httpOnly refresh cookie, and rotate refresh tokens. Never put secrets in the bundle.
Other points: use an established identity provider (OIDC with PKCE) rather than rolling your own, handle 401 responses globally by clearing the session and redirecting, protect against open redirects when using a from parameter, and apply rate limiting and multi-factor authentication on the server. In Next.js, check sessions in Server Components, route handlers and middleware or the proxy layer, and again inside each Server Action.
The example uses a memory router with a loader guard.
import { RouterProvider, createMemoryRouter, redirect, useNavigate } from 'react-router';
const session = { user: null };
function requireUser() {
if (!session.user) throw redirect('/login');
return session.user;
}
function Login() {
const navigate = useNavigate();
return (
<main>
<h1>Login page</h1>
<button
onClick={() => {
session.user = 'Asha';
navigate('/dashboard');
}}
>
Log in
</button>
</main>
);
}
function Dashboard() {
const navigate = useNavigate();
return (
<main>
<h1>Dashboard for {session.user}</h1>
<button
onClick={() => {
session.user = null;
navigate('/login');
}}
>
Log out
</button>
</main>
);
}
const router = createMemoryRouter(
[
{ path: '/login', Component: Login },
{ path: '/dashboard', loader: requireUser, Component: Dashboard, HydrateFallback: () => <p>Checking session...</p> },
],
{ initialEntries: ['/dashboard'] }
);
export default function App() {
return <RouterProvider router={router} />;
}The session here is a plain object only to keep the example short. A real app asks the server and also checks on every request. The check opened /dashboard while logged out, logged in, and logged out again. Output of the run: opened /dashboard while logged out: Login page after logging in: Dashboard for Asha after logging out: Login page
Key points
- The client guard is UX. The server must enforce authorization on every request.
- Use route loaders or a guard component, and remember the destination for a return after login.
- Load the session from the server and show a loading state to avoid flicker.
- Prefer httpOnly, Secure, SameSite cookies with CSRF protection over localStorage tokens.
- Use a proven identity provider and handle 401 responses centrally.
Common mistakes
- Believing a client-side guard secures data.
- Storing long-lived tokens in localStorage.
- Redirecting from an effect after the protected page has rendered, causing a flash of content.
- Using an unvalidated from parameter and creating an open redirect.
- Not clearing cached data on logout.
Follow-ups
- How do you protect state-changing requests with cookies from CSRF?
- How would you implement role-based access in routes?
- How would you refresh an expired access token without logging the user out?
Tips
- Start with "the server enforces". It is the central security point.
- Compare cookie and localStorage storage, with the XSS and CSRF trade-off.
- Mention using an established identity provider.