Authentication

Build first-party email/password authentication with JWT sessions, email verification, and protected dashboard routes.

Build first-party authentication for a Next.js app using email/password login, signed JWT session cookies, verified-email gates, and revocable sessions.

What You Will Build#

  • Sign-up and sign-in endpoints
  • A signed session cookie for dashboard access
  • Middleware protection for authenticated pages
  • Email verification for sensitive actions
  • Session revocation and sign-out-all support

Prerequisites#

  • Next.js App Router project
  • Prisma or another database ORM
  • AUTH_JWT_SECRET set in your environment
  • Email transport configured for verification and password reset emails

Step 1: Configure Auth Secrets#

Add the minimum auth configuration first.

Loading code block...

Step 2: Add a User Model#

Your user table needs password and verification fields.

Loading code block...

Step 3: Create Session Utilities#

Use a signed JWT cookie for the web session.

Loading code block...

Step 4: Implement Sign-Up and Sign-In#

Hash passwords, create the user, and set the session cookie.

Loading code block...

Step 5: Protect the Dashboard#

Use middleware so protected pages redirect before rendering.

Loading code block...

Step 6: Add Email Verification#

Keep billing, API key creation, invites, and device authorization behind verified email.

Loading code block...

Step 7: Add Session Revocation#

JWT cookies are not enough if you need sign-out-all. Store a server-side session record or refresh token row so you can revoke sessions early and rotate them safely.

Recommended controls:

  • Rotate the session after a fixed age
  • Revoke the current session on sign-out
  • Support sign-out-all from account settings
  • Invalidate sessions after password reset or account deletion

Security Review Checklist#

  • Passwords are hashed with bcrypt or argon2
  • Auth routes are rate-limited
  • Sensitive routes require verified email
  • Cookies are httpOnly, secure, and sameSite=lax
  • Password reset and verification tokens expire
  • Session revocation is backed by the database

What You Learned#

  • How to issue first-party JWT sessions
  • How to protect dashboard routes in middleware
  • How to gate sensitive actions behind verified email
  • Why server-side session revocation still matters with JWTs

Next Steps#

Resources#