ReactHard

Authentication flow

A complete authentication flow covers loading the current session on startup, signing in, protecting routes, sending credentials with API requests, handling expired sessions, and signing out. In a React SPA the safest common setup keeps the session in an httpOnly cookie set by the server, exposes the user through an auth context or query, guards routes with a component or router middleware, and redirects back to the original page after login.

Steps

  1. Bootstrap: on load, call /api/me (cookie sent automatically with credentials: "include"). Show a loading state until it resolves.
  2. Login: submit credentials (or start OAuth or a passkey ceremony); the server sets the session cookie and returns the user; store the user in context.
  3. Protect routes: if there is no user, redirect to /login?next=/original (or state.from); otherwise render the route.
  4. API calls: include credentials; on a 401, try a refresh once (if using refresh tokens), otherwise clear the user and redirect to login.
  5. Logout: call the server to clear the cookie, reset client caches (queryClient.clear()), redirect.
  6. Authorization: check roles for UI, but the server must enforce permissions on every endpoint.

Why not localStorage tokens

Tokens in localStorage can be stolen by any XSS. If you need bearer tokens, keep the access token in memory (short-lived) and the refresh token in an httpOnly cookie.

Security details

CSRF protection for cookie-based APIs (SameSite=Lax cookies plus a CSRF token or origin checks for state-changing requests), rate-limited login, generic error messages ("Invalid email or password"), HTTPS only.

In practice

Use an auth provider or library (Auth0, Clerk, WorkOS, Supabase, Better Auth) and your router's middleware or loaders.

Code example

tsx
1import { createContext, use, useEffect, useState } from "react";
2import { Navigate, Outlet, useLocation, useNavigate } from "react-router";
3
4type User = { id: string; name: string; role: "user" | "admin" };
5type AuthValue = { user: User | null; status: "loading" | "ready"; login: (email: string, pw: string) => Promise<void>; logout: () => Promise<void> };
6const AuthContext = createContext<AuthValue | null>(null);
7export const useAuth = () => { const v = use(AuthContext); if (!v) throw new Error("No AuthProvider"); return v; };
8
9export function AuthProvider({ children }: { children: React.ReactNode }) {
10 const [user, setUser] = useState<User | null>(null);
11 const [status, setStatus] = useState<"loading" | "ready">("loading");
12
13 useEffect(() => {
14 fetch("/api/me", { credentials: "include" }).then((r) => (r.ok ? r.json() : null)).then(setUser).finally(() => setStatus("ready"));
15 }, []);
16
17 const login = async (email: string, password: string) => {
18 const r = await fetch("/api/login", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password }) });
19 if (!r.ok) throw new Error("Invalid email or password");
20 setUser(await r.json());
21 };
22 const logout = async () => { await fetch("/api/logout", { method: "POST", credentials: "include" }); setUser(null); };
23
24 return <AuthContext value={{ user, status, login, logout }}>{children}</AuthContext>;
25}
26
27export function RequireAuth() {
28 const { user, status } = useAuth();
29 const location = useLocation();
30 if (status === "loading") return <p>Checking session…</p>;
31 if (!user) return <Navigate to={`/login?next=${encodeURIComponent(location.pathname)}`} replace />;
32 return <Outlet />;
33}
34
35export function LoginPage() {
36 const { login } = useAuth();
37 const navigate = useNavigate();
38 const next = new URLSearchParams(useLocation().search).get("next") ?? "/";
39 return (
40 <form action={async (fd) => { await login(String(fd.get("email")), String(fd.get("password"))); navigate(next, { replace: true }); }}>
41 <input name="email" type="email" required /> <input name="password" type="password" required /> <button>Sign in</button>
42 </form>
43 );
44}

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