Two-factor auth (2FA)
Add a second factor with a TOTP app (Google Authenticator, 1Password). The flow layers on top of the existing NextAuth session: store a secret per user, verify a code, and require it before sensitive actions.
Store a per-user secret
Add totp_secret and totp_enabled columns to users. Generate the secret with a TOTP library when the user opts in.
npm install otplib qrcodeEnroll
Show a QR code built from the secret, then verify the first code before setting totp_enabled. This confirms the user's app is in sync.
import { authenticator } from "otplib";
const secret = authenticator.generateSecret();
const isValid = authenticator.verify({ token, secret });Gate sensitive actions
For users with 2FA enabled, require a fresh code before high-risk actions (changing email, deleting the account, managing billing). Apply the check in the relevant API routes, alongside the session check.
Provide recovery codes
Generate one-time recovery codes at enrollment and store their hashes. A user who loses their device needs a way back in, or they are locked out for good.
