JWT Sessions

Build first-party email/password authentication with signed session cookies, email verification, and revocable sessions.

Build first-party authentication with email/password sign-in, signed session cookies, and server-side revocation.

What This Recipe Covers#

  • Email/password sign-up and sign-in
  • Signed JWT session cookies
  • Route protection for dashboard pages
  • Email verification gates for sensitive actions
  • Session revocation and sign-out-all controls

Prerequisites#

  • Next.js App Router project
  • User table in your database
  • AUTH_JWT_SECRET set to a 32+ character secret
  • Email transport configured if you want verification emails

1. Session Utilities#

Loading code block...

2. Sign-Up Route#

Loading code block...

3. Sign-In Route#

Loading code block...

4. Protect Dashboard Routes#

Loading code block...

5. Gate Sensitive Actions Behind Verified Email#

Loading code block...

6. Add Server-Side Session Revocation#

If you need sign-out-all or session rotation, store a server-side session record alongside the JWT:

Loading code block...

Use the database record to invalidate the cookie even before the JWT expires.

Security Checklist#

  • Use a long random AUTH_JWT_SECRET
  • Hash passwords with bcrypt or argon2
  • Keep cookies httpOnly, secure, and sameSite=lax
  • Rotate sessions periodically
  • Require verified email for billing, keys, invites, and device authorization
  • Add rate limiting on sign-in, sign-up, and password reset routes