A complete client-side authentication layer that handles login, session persistence, token refresh, OAuth integration, and authorization — without leaking secrets or shipping unnecessary bytes. Every modern frontend needs this: Next.js apps with NextAuth, SPAs using Supabase/Clerk/Auth0, custom stacks with JWT+refresh, and even server-rendered apps with session cookies.
What looks like a simple login form conceals a surprisingly complex system. The auth layer must persist credentials securely, silently refresh expiring tokens, defend against XSS and CSRF, handle concurrent refresh storms, manage role-based access control, and recover gracefully from network failures — all while delivering a seamless UX. One mistake — an unguarded refresh endpoint, a token leaked via localStorage, a missingSameSite attribute — and the entire system is compromised.
Here is the high-level API shape the auth layer exposes to the rest of the application:
const { user, isAuthenticated, isLoading, login, logout, refreshToken } = useSession();
// Check auth state anywhere in your app
if (isLoading) return <Spinner />;
if (!isAuthenticated) return <LoginPage />;
// Access user info
console.log(user?.name, user?.roles);
// Log out
await logout();The consumer calls useSession() and gets back the current user state, login/logout helpers, and an auto-refreshing access token. The hard work — token storage, refresh logic, race condition handling, CSRF protection — happens inside the provider. Let's walk through how to design this layer systematically.