ReactMedium

Auth in React?

Authentication in a React app means verifying who the user is (login), keeping a session, and showing or hiding UI accordingly, while the server enforces access to data. The recommended setup is a server-issued session in an httpOnly, secure, SameSite cookie, an auth context or library hook for the current user on the client, route protection in loaders or guard components, and an auth provider or library instead of hand-rolled crypto.

Building blocks

  1. Login: form posts credentials (or starts an OAuth or passkey flow) to the server.
  2. Session: the server sets a cookie with a session ID or signed token. httpOnly keeps it away from JavaScript, which protects it from XSS.
  3. Current user on the client: fetch /api/me on load and store it in context or a query cache.
  4. Protected routes: redirect unauthenticated users (router middleware or loaders, guard components, framework Proxy).
  5. Authorization: the API checks permissions on every request; the client only hides UI.
  6. Logout: a server endpoint clears the cookie; the client clears cached user data.

Tokens in localStorage?

Storing JWTs in localStorage is simple but exposes them to any XSS. Prefer cookies; if you must use bearer tokens (mobile or third-party APIs), keep access tokens short-lived and in memory, with refresh tokens in httpOnly cookies.

Libraries and providers

Auth0, Clerk, WorkOS, Supabase Auth, Firebase Auth, Better Auth, Auth.js (now maintained by the Better Auth team). Passkeys (WebAuthn) are widely supported and phishing-resistant.

UX details

Loading state while the session is checked, preserve the destination URL for after login, handle expired sessions gracefully with a re-login prompt.

Code example

tsx
1import { createContext, use, useEffect, useState } from "react";
2
3type User = { id: string; name: string; role: "user" | "admin" };
4type Auth = { user: User | null; loading: boolean; login: (email: string, password: string) => Promise<void>; logout: () => Promise<void> };
5
6const AuthContext = createContext<Auth | null>(null);
7
8export function AuthProvider({ children }: { children: React.ReactNode }) {
9 const [user, setUser] = useState<User | null>(null);
10 const [loading, setLoading] = useState(true);
11
12 useEffect(() => {
13 fetch("/api/me", { credentials: "include" }) // session lives in an httpOnly cookie
14 .then((r) => (r.ok ? r.json() : null))
15 .then(setUser)
16 .finally(() => setLoading(false));
17 }, []);
18
19 async function login(email: string, password: string) {
20 const res = await fetch("/api/login", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password }) });
21 if (!res.ok) throw new Error("Invalid credentials");
22 setUser(await res.json());
23 }
24
25 async function logout() {
26 await fetch("/api/logout", { method: "POST", credentials: "include" });
27 setUser(null);
28 }
29
30 return <AuthContext value={{ user, loading, login, logout }}>{children}</AuthContext>;
31}
32
33export function useAuth() {
34 const ctx = use(AuthContext);
35 if (!ctx) throw new Error("useAuth must be inside AuthProvider");
36 return ctx;
37}

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