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
- Login: form posts credentials (or starts an OAuth or passkey flow) to the server.
- Session: the server sets a cookie with a session ID or signed token.
httpOnlykeeps it away from JavaScript, which protects it from XSS. - Current user on the client: fetch
/api/meon load and store it in context or a query cache. - Protected routes: redirect unauthenticated users (router middleware or loaders, guard components, framework Proxy).
- Authorization: the API checks permissions on every request; the client only hides UI.
- 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
1import { createContext, use, useEffect, useState } from "react";23type 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> };56const AuthContext = createContext<Auth | null>(null);78export function AuthProvider({ children }: { children: React.ReactNode }) {9 const [user, setUser] = useState<User | null>(null);10 const [loading, setLoading] = useState(true);1112 useEffect(() => {13 fetch("/api/me", { credentials: "include" }) // session lives in an httpOnly cookie14 .then((r) => (r.ok ? r.json() : null))15 .then(setUser)16 .finally(() => setLoading(false));17 }, []);1819 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 }2425 async function logout() {26 await fetch("/api/logout", { method: "POST", credentials: "include" });27 setUser(null);28 }2930 return <AuthContext value={{ user, loading, login, logout }}>{children}</AuthContext>;31}3233export 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.