Auth guard / protected route
The code gate in front of a page or endpoint that bounces anyone without a valid session to the login screen.
See it
What it is
An auth guard is the check that sits in front of a page or an API route and asks 'is there a valid session here?' before anything renders. No session, no page: redirect to /login, usually with a 'return to' parameter so the user lands back where they were trying to go. In Next.js this is middleware or a layout check, in React Router a wrapper route, in Express a middleware function. Same idea everywhere.
Prefer a default-deny shape: guard a whole path prefix like /app or /dashboard and list the public exceptions, rather than remembering to add a guard to each new page. Guarding a layout instead of every leaf route is the version that survives a growing app.
The big misconception: a client-side guard is UX, not security. Hiding a route in the browser does nothing about someone calling your API directly with curl, so every protected endpoint needs its own server-side check. Watch the flicker too, since a guard that renders the page then redirects flashes private-looking content for a frame. Check on the server or hold a loading state until the session resolves. And keep authentication (are you logged in) separate from authorization (are you allowed), because a guard that only checks the first will happily show an admin page to a normal user.
Ask AI for it
Add route protection, and treat page navigation and API calls as two different cases. For protected pages, guard the /app prefix by default with a server-side check (Next.js middleware or a server layout) that reads the session cookie and redirects unauthenticated visitors to /login?next=<original-path>. Validate that return path before using it: accept only a same-origin relative path starting with a single slash, reject anything with a scheme, a host, or a protocol-relative '//' prefix, and fall back to the dashboard when it fails the check, so the parameter cannot become an open redirect. For API routes, never redirect to a login page: return a JSON 401 with a WWW-Authenticate header, so clients get a parseable error instead of a login page's HTML. Return 403, not 401 and not a redirect, when the caller is authenticated but lacks the permission. Keep an explicit public allowlist for /, /login, /signup, and marketing pages. Enforce every check independently on the server, including tenant and resource ownership on the record being touched, since the client guard is only UX. Render a loading state rather than page content while the session resolves so nothing private flashes.