Authentication: JWT, NextAuth and Guards
Harry
· 28 Sep 2026
· 1 views
Log in to track your progress and mark lessons complete.
Sponsored
Token Flow (Any Backend)
// login: POST /api/auth/login -> { token, user }
localStorage.setItem("token", token)
// every request carries it (Axios interceptor from lesson 11)
// logout: remove token + redirect to /loginStore JWT in memory or httpOnly cookies (XSS-safe); localStorage is convenient but XSS-readable - know the trade-off.
NextAuth.js (Next.js Apps)
npm i next-auth
// app/api/auth/[...nextauth]/route.js - providers: Google, GitHub, Credentials
// client: useSession() gives { data: session, status }Route Guards
// React Router:
function Guard({ children }) {
const { user, loading } = useAuth()
if (loading) return <p>Loading…</p>
return user ? children : <Navigate to="/login" replace />
}
// Next.js: middleware.js checks the session cookie per routeRoles (Admin vs User)
Decode role from the token, hide admin links AND enforce on the API - frontend hiding alone is decoration, not security.
Key Points
- Tokens in headers, refresh before expiry.
- Guard routes and APIs - never only the UI.
- NextAuth for Next.js, manual JWT for Vite SPAs.