How to Implement TOTP Two-Factor Authentication in a Next.js SaaS
Implement production-ready TOTP two-factor authentication in Next.js App Router with AES-256 secret encryption, Redis rate limiting, and hashed backup codes.
Two-factor authentication using TOTP — Time-Based One-Time Passwords — is the most widely implemented second factor in SaaS products in 2026, and also one of the most poorly implemented. Most teams add TOTP by following a tutorial that covers the happy path: generate a secret, show a QR code, verify a code. What those tutorials skip are the production security requirements that turn a working demo into a hardened authentication system: encrypting the TOTP secret at rest, limiting verification attempts across serverless instances, issuing hashed single-use backup codes, and requiring a fresh TOTP challenge before sensitive operations even when the user is already authenticated.
This guide covers the full production-grade TOTP implementation for Next.js App Router — from library selection to step-up authentication — including the specific security controls that separate a secure implementation from one that passes a code review but fails under a targeted attack. For a broader look at authentication mistakes in AI-assisted apps, see common authentication mistakes in vibe-coded apps.
Why TOTP Remains the Default 2FA for SaaS in 2026
Passkeys and hardware security keys are more phishing-resistant than TOTP, but adoption among SaaS end users is still uneven. TOTP works with every authenticator app — Google Authenticator, Authy, 1Password, Bitwarden, Microsoft Authenticator — requires no hardware, and has no dependency on device-specific APIs. For a SaaS with a broad user base, TOTP is still the right starting point for 2FA. The goal of this guide is to implement it correctly, not to argue for it over alternatives.
- →TOTP uses a shared secret and the current time window (30-second intervals by default) to generate a 6-digit code. The server and the authenticator app independently compute the same HMAC-SHA1 digest. No network call is required at verification time.
- →The RFC 6238 standard (TOTP) is built on RFC 4226 (HOTP). Both are universally supported by authenticator apps. TOTP is the time-based variant; HOTP is counter-based and less common in SaaS contexts because counter desynchronization is a support burden.
- →TOTP's main security risk is that the shared secret is a static value stored in your database. If the database is breached, every user's TOTP secret is compromised. This is why encrypting the secret at rest — not just at the database volume level — is a production requirement, not a nice-to-have.
- →An attacker who intercepts a valid 6-digit code has a 30-second window to replay it. Marking codes as used after verification (tracking recently used TOTP windows) closes this replay vector at the cost of one additional database write per successful verification.
Choosing a TOTP Library: otplib vs speakeasy in Next.js App Router
Library choice affects both the security guarantees you get out of the box and the compatibility of your implementation with the Next.js App Router runtime. The two most commonly referenced libraries in existing tutorials are speakeasy and otplib. Only one of them should be used in a new 2026 project.
- →speakeasy has not received a commit since 2017 and has known open security issues in its dependency tree. It still appears in many tutorials because it dominated the ecosystem before otplib matured. Do not use it in new projects.
- →otplib is the correct choice. It has approximately 3.8 million weekly npm downloads, is TypeScript-native, and explicitly supports both Node.js and Edge Runtime environments. Import from otplib/preset-default for Node.js route handlers and otplib/preset-browser for edge middleware or Vercel Edge Functions.
- →otpauth is a third option — a lightweight, standards-compliant library — appropriate when bundle size is a constraint in Edge Runtime. It lacks some of otplib's convenience APIs but produces RFC-compliant output. Either otplib or otpauth is acceptable; speakeasy is not.
- →otplib exposes the authenticator namespace for TOTP operations. The key methods are authenticator.generateSecret() to produce a random base32-encoded secret and authenticator.verify({ token, secret }) to validate a user-submitted code. Both take the decrypted secret — the encryption and decryption layer is your responsibility, not the library's.
Generating and Encrypting TOTP Secrets at Rest (AES-256-GCM)
The TOTP shared secret is a long-term static value. Storing it in plaintext in your database means that a SQL injection, a misconfigured Supabase RLS policy, or a database backup leak exposes every user's second factor simultaneously. AES-256-GCM encryption at the application layer — above the database — prevents this. The key material lives in your environment variables, not in the database.
- →Step 1 — Generate the secret. Call authenticator.generateSecret() from otplib. This returns a base32-encoded string of 20 random bytes. This is the plaintext secret that will be shared with the user's authenticator app via a QR code and stored (encrypted) in your database.
- →Step 2 — Derive an encryption key. Use Node.js crypto.scryptSync(process.env.TOTP_ENCRYPTION_KEY, salt, 32) to derive a 256-bit AES key from a secret environment variable. The salt should be the user's ID or a fixed application-level salt stored separately from the ciphertext. Never use the raw environment variable directly as the AES key.
- →Step 3 — Encrypt with AES-256-GCM. Create an IV with crypto.randomBytes(16). Pass the IV, key, and plaintext secret to crypto.createCipheriv('aes-256-gcm', key, iv). Call cipher.getAuthTag() after cipher.final() to retrieve the GCM authentication tag. Store iv (hex), authTag (hex), and ciphertext (hex) together — all three are required for decryption.
- →Step 4 — Decrypt on verification. Reconstruct the decipher with crypto.createDecipheriv, set the auth tag with decipher.setAuthTag(), and call decipher.update() followed by decipher.final(). If the auth tag does not match, GCM decryption throws — this is not an error to suppress, it means the ciphertext has been tampered with.
- →Step 5 — Rotate the secret on suspicious activity. If you detect a device compromise or a user reports they did not set up 2FA, invalidate the stored encrypted secret and require re-enrollment. The same rotation flow should be triggered when a user exhausts their backup codes.
Building the TOTP Enrollment Flow: QR Codes and First Verification
The enrollment flow is the first surface where most implementations go wrong. Generating the secret and showing the QR code before the user has verified a code from their authenticator app means that if the user mis-scans or uses a broken app, they are locked out. Never persist the TOTP secret or mark TOTP as enabled until the user successfully verifies the first code.
- →On the enrollment page, generate the secret server-side and store it temporarily in a secure, server-signed session cookie — not in the database, and not in localStorage. The secret is not committed until the user verifies a code.
- →Build the OTP URI using the otpauth format: otpauth://totp/{issuer}:{userEmail}?secret={base32Secret}&issuer={issuer}&algorithm=SHA1&digits=6&period=30. The issuer should be your application name. Pass this URI to the qrcode npm package to generate a data URL for the QR code rendered in the browser.
- →On the verification step, decrypt the temporary secret from the session cookie, call authenticator.verify({ token: userSubmittedCode, secret: decryptedSecret }), and check the result. If verification succeeds, persist the encrypted secret to the database and set mfa_enabled = true on the user record — in the same database transaction.
- →Generate the backup codes at the same point (see the next section). Present them to the user immediately after successful enrollment with a clear warning that they cannot be retrieved again. Users who close the page without saving backup codes will not have them.
- →Add a window option to authenticator.verify to tolerate minor clock skew. otplib's default window is 1, which accepts codes from the previous and next time windows and tolerates up to 60 seconds of clock difference — a reasonable default for most deployments.
Hashed, Single-Use Backup Codes: Implementation and Storage
Backup codes are the recovery path when a user loses access to their authenticator app. If backup codes are stored in plaintext, a database breach gives an attacker recovery access for every 2FA-enabled account. Storing them as bcrypt hashes — the same approach used for passwords — means a breach does not immediately compromise backup codes.
- →Generate 10 backup codes at enrollment time. Each code should be 10 to 12 random characters generated with crypto.randomBytes. Format them as XXXX-XXXX for readability. These are shown to the user exactly once and never stored in plaintext on the server.
- →Hash each code with bcrypt at a cost factor of 10. Store the 10 hashes in a backup_codes table with columns (user_id, code_hash, used_at, created_at). The used_at timestamp is null until the code is consumed.
- →On backup code verification, iterate through the user's unused hashes and call bcrypt.compare(submittedCode, storedHash). On a match, immediately set used_at to the current timestamp in the same transaction as the session establishment. Never reuse a backup code that has used_at set.
- →Rate limit backup code attempts as aggressively as TOTP attempts — these are equally high-value targets for a credential stuffing attack. After three failed backup code attempts, lock the account and trigger an email notification to the account owner.
- →Provide a regeneration flow. When a user has fewer than three remaining backup codes, surface a prompt to regenerate. Regenerating invalidates all existing codes and issues a new set of 10. Mark old codes with a regenerated_at timestamp rather than deleting them to preserve the audit trail.
Rate Limiting TOTP Verification in Serverless Next.js (Upstash + Redis)
In-process rate limiting — tracking attempts in a module-level Map or in-memory counter — breaks in serverless environments where each invocation may run in a different process or container. Next.js deployed on Vercel is stateless by default: an in-memory limit resets between invocations, which means an attacker can bypass it by sending requests that land on different instances. Redis-backed rate limiting with Upstash Ratelimit provides a consistent counter across all instances.
- →Install @upstash/ratelimit and @upstash/redis. Initialize a Ratelimit instance at module scope with a sliding window algorithm: new Ratelimit({ redis, limiter: Ratelimit.slidingWindow(5, '15m') }). This allows 5 TOTP verification attempts per user per 15-minute window.
- →Use the user's ID as the rate limit key — not their IP address. IP-based limiting is bypassed with rotating proxies and fails for shared corporate NAT addresses. User-ID rate limiting is more precise and targets the actual attack vector: credential stuffing against a known account.
- →Check the rate limit before decrypting the TOTP secret or running bcrypt. The ratelimit.limit(userId) call returns { success, remaining, reset }. If success is false, return 429 Too Many Requests with a Retry-After header derived from the reset timestamp.
- →Apply a separate, stricter rate limit to the enrollment endpoint. An attacker who can repeatedly re-trigger enrollment can probe for timing differences in secret generation. Limit enrollment to 3 attempts per user per hour.
- →Log rate limit breaches to your audit log with the user ID, endpoint, and timestamp. Consecutive rate limit events on the same account are a signal worth alerting on — a user attempting TOTP brute force is a live account takeover attempt in progress.
Step-Up Authentication: Requiring TOTP for Specific Routes in App Router
Most TOTP implementations check the second factor once at login and then trust the session for its full lifetime. Step-up authentication takes a different approach: sensitive operations — billing changes, API key management, data exports, team permission changes — require a fresh TOTP challenge even if the user passed 2FA hours ago at login. This limits the blast radius of a session hijack considerably.
- →Add an mfa_verified_at timestamp field to your session. Set it to the current time when a user successfully passes the TOTP challenge at login. Store it in the signed session object, not in a cookie the browser can modify.
- →In your Next.js middleware, for routes in a designated sensitive group such as /settings/billing, /settings/api-keys, or /admin, check whether mfa_verified_at is within your step-up window (60 minutes is a reasonable default). If it is older or absent, redirect to the step-up challenge page.
- →The step-up challenge page requires the user to enter a TOTP code without re-entering their password. On success, update mfa_verified_at in the session and redirect back to the original destination. This confirms the user still has possession of their authenticator device.
- →Be careful about the CVE-2025-29927 middleware-bypass vulnerability patched in Next.js 15.2.3. Middleware-only authorization checks can be bypassed in affected versions. Add a redundant server-side check inside the Route Handler in addition to the middleware redirect.
- →For step-up flows that protect very high-value operations such as deleting an account or exporting all user data, consider shortening the window to 5 or 10 minutes and requiring re-entry even if the user passed the step-up challenge recently.
Session Regeneration After TOTP Verification
Session fixation is an underappreciated risk in multi-step authentication flows. The attack works by injecting a known session ID before the user completes login; if the server does not issue a new session ID after the TOTP challenge passes, the attacker's known session ID is now fully authenticated. Most implementations regenerate the session after the password check but not after the TOTP challenge — this is the gap. For a full treatment of account takeover patterns that TOTP helps close, see account takeover prevention in multi-tenant SaaS.
- →Issue a new session ID every time the authentication state escalates. For a two-step login (password check then TOTP challenge), regenerate the session ID at the TOTP step, not just at the password step. The session should change each time it gains a new privilege level.
- →With NextAuth.js, session regeneration is handled by calling signIn at the end of a custom credentials flow. The session token is re-issued and the previous token is invalidated. For iron-session, call req.session.destroy() and start a new session with the authenticated identity after TOTP passes.
- →Store the pre-TOTP session and the post-TOTP session separately and do not share any long-lived identifiers between them. A session ID that persists from the unauthenticated state into the fully authenticated state is a session fixation vector.
- →Add session invalidation on TOTP disable. When a user turns off 2FA, invalidate all existing sessions and require a fresh login. The post-disable session should not retain the mfa_verified_at field from before the change.
Frequently Asked Questions
Should I use otplib or speakeasy for TOTP in Next.js in 2026?
Use otplib. speakeasy has not been maintained since 2017 and has unresolved dependency vulnerabilities. otplib has approximately 3.8 million weekly downloads, is TypeScript-native, and explicitly supports Edge Runtime via its browser preset. otpauth is a viable alternative if bundle size is a constraint in Edge Runtime.
How do I encrypt the TOTP secret before storing it in my database?
Use AES-256-GCM with a key derived from a server-side environment variable via crypto.scryptSync. Store the IV, GCM authentication tag, and ciphertext in separate columns alongside the user record. Never store the raw base32 secret — it is a static long-term credential that must be treated like a password hash.
How do I rate limit TOTP verification in a serverless Next.js deployment?
Use @upstash/ratelimit with a sliding window counter keyed on the user ID. In-memory rate limiting breaks in serverless environments where requests are served by different processes or containers. Set a limit of 5 attempts per 15-minute window for verification and apply a stricter limit to backup code attempts.
What is step-up authentication and when should I require it?
Step-up authentication requires a fresh TOTP challenge before specific sensitive operations — billing changes, API key creation, data exports — even if the user has an active authenticated session. Use it on any action that would cause significant harm if executed via a hijacked session. Store mfa_verified_at in the signed session and check its age before allowing access to protected routes.
How is TOTP different from passkeys, and should I implement both?
Passkeys use device-bound asymmetric credentials and are phishing-resistant by design — there is no shared secret to steal from your database. TOTP uses a static shared secret and a time-based algorithm, which means a database breach can expose all TOTP secrets simultaneously. For most SaaS teams in 2026, TOTP is the right starting point because every authenticator app supports it. Passkeys should be offered as a parallel option and can gradually become the default as device support matures across your user base.
How Belsoft Helps Teams Ship Secure 2FA
Adding TOTP to a Next.js SaaS is a multi-layer implementation that spans library selection, cryptographic key management, session architecture, and rate limiting infrastructure. When one layer is weak — an unencrypted secret, an in-memory rate limiter, a session that is not regenerated after the TOTP challenge — the second factor provides less protection than it appears to. A Belsoft security audit reviews the full authentication implementation: the TOTP enrollment and verification flow, backup code storage, session lifecycle, and rate limiting — by hand, the way a targeted attacker would probe it, not the way a scanner would.
Before the manual audit, run DeployReady to clear the automated baseline — missing headers, exposed secrets, and RLS gaps that the tool catches in minutes. The manual audit then focuses on what automation cannot replicate: logic flaws in the TOTP flow, session fixation vectors, and step-up authentication bypass paths. If you are preparing for SOC 2 or responding to a security questionnaire from an enterprise customer, the combination of DeployReady for automated hygiene and a Belsoft audit for manual depth is the fastest path to a defensible posture. Book a call to scope the work.
“A second factor you cannot safely store, rate limit, and regenerate sessions around is a liability dressed as a security control.”
Written by
Marco Silva
Security Engineer, Belsoft Solutions
More from the blog
Ready to partner?
Let's talk about your company.
30 minutes. No pitch. We talk through how you run today and where AI and automation would help.
Book a free audit
