Authentication: JWT, NextAuth and Guards

Harry · 28 Sep 2026 · 1 views
Log in to track your progress and mark lessons complete.

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 /login

Store 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 route

Roles (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.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in