DEV Community

Cover image for How to Implement TOTP Authentication in Next.js: Secure 2FA Login Step-by-Step
vdelitz for Corbado

Posted on • Originally published at corbado.com

How to Implement TOTP Authentication in Next.js: Secure 2FA Login Step-by-Step

Read the full article here


Introduction: Why Add TOTP to Your Next.js Login?

Implementing secure authentication is essential for protecting your users and their sensitive data. Time-based One-Time Password (TOTP) is an established two-factor authentication (2FA) method that strengthens app security by requiring users to enter a unique, time-limited code from an authenticator app. In this Next.js authentication guide, you’ll learn how to set up TOTP in your Next.js project to create a robust and user-friendly login experience.


Getting Started: Set Up Your Next.js Project

To add TOTP in Next.js, start with a solid project foundation. You’ll need experience with React, TypeScript, Node.js and MongoDB. Create a new project with:

npx create-next-app@latest nextjs-auth-methods

Choose TypeScript, ESLint, Tailwind CSS, and organize your code in the /src directory. Set up a .env.local file for environment variables (such as MongoDB URL and API credentials). This makes your project scalable and secure.


Install Dependencies for TOTP in Next.js

For generating and verifying time-based codes, use Speakeasy and QRCode libraries:

npm install speakeasy qrcode

Speakeasy handles TOTP code creation and validation, while QRCode generates scannable codes for use with apps like Google Authenticator.


Database Model: Storing TOTP Secrets in Next.js

Create a Mongoose schema in src/models/Totp.ts with fields for the user’s email, TOTP secret, and a boolean for TOTP activation. This schema ensures each user’s secret is unique and stored securely.


Core API Routes for TOTP Authentication

Add dedicated API endpoints for handling TOTP flows:

  • Generate TOTP Secret & QR Code (/api/auth/totp/generate): Produces a TOTP secret and QR code, saving the secret in MongoDB.
  • Check TOTP Status (/api/auth/totp/status): Returns if TOTP is already enabled for the user.
  • Verify TOTP Code (/api/auth/totp/verify): Validates the TOTP code users enter and activates TOTP if correct.

This flow enables codes to be scanned by an authenticator app and ensures that only valid tokens are accepted.


Building the Next.js Authentication UI

In src/app/totp/page.tsx, create a React component to guide users through the 2FA process:

  1. Collect email to start login.
  2. Provide a “Generate QR Code” button. Upon clicking, display a QR code for the user to scan in their authenticator app.
  3. Offer an input for users to enter the one-time code from their app.
  4. After successful verification, confirm TOTP is enabled for future logins.

Good state management and clear UI feedback enhance the user experience for TOTP authentication in Next.js.


Testing Your Next.js TOTP Flow

Once implemented:

  • Navigate to /totp
  • Enter your email and log in
  • Generate and scan the QR code
  • Input and verify the TOTP token

Upon successful verification, two-factor authentication is enabled for your Next.js login page. On each subsequent login, users will authenticate using the TOTP code from their authenticator app.


Best Practices for Secure Authentication in Next.js

  • Use authentication libraries like NextAuth.js or Auth0 to reduce development and security risks.
  • Always combine TOTP with another method (like passwords) for true multi-factor authentication.
  • Never store passwords in plain text, but use secure hashing.
  • Enforce HTTPS, rate limiting and robust session management.
  • Monitor authentication logs for unusual activity and keep an eye on possible brute-force attacks.
  • Thoroughly validate emails and prohibit use of disposable addresses for registration.

Conclusion

Adding Time-based One-Time Password authentication to your Next.js login page provides a practical, secure layer of protection for your users. By combining a straightforward project setup, dedicated API routes and a user-centric UI, you’ll deliver a reliable 2FA solution that promotes trust in your application.

For advanced topics such as integrating passkeys, passwordless login or using popular authentication libraries alongside TOTP, read the full article and explore the complete code examples here: https://www.corbado.com/blog/nextjs-totp-login

Top comments (0)