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_SECRETset in your environment- Email transport configured for verification and password reset emails
Step 1: Configure Auth Secrets#
Add the minimum auth configuration first.
Step 2: Add a User Model#
Your user table needs password and verification fields.
Step 3: Create Session Utilities#
Use a signed JWT cookie for the web session.
Step 4: Implement Sign-Up and Sign-In#
Hash passwords, create the user, and set the session cookie.
Step 5: Protect the Dashboard#
Use middleware so protected pages redirect before rendering.
Step 6: Add Email Verification#
Keep billing, API key creation, invites, and device authorization behind verified email.
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
bcryptorargon2 - Auth routes are rate-limited
- Sensitive routes require verified email
- Cookies are
httpOnly,secure, andsameSite=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