This example demonstrates how to implement email/password authentication with two-factor authentication (2FA) using Next.js and Auth.js. The 2FA codes are delivered via email using NotificationAPI.
- ✨ Email/Password authentication
- 🔒 Two-factor authentication (2FA) via email
- 📧 Email delivery using NotificationAPI
- 🗄️ Persistent sessions with Prisma
- 🔐 Secure password hashing with bcrypt
- 🎨 Clean and modern UI with Tailwind CSS
- User enters email and password
- If credentials are valid, a 6-digit 2FA code is generated and sent via email
- User enters the 2FA code to complete authentication
- 2FA codes expire after 10 minutes for security
-
Clone the repository:
git clone https://github.com/notificationapi-com/notificationapi-authjs-nextjs-email-2fa-example cd notificationapi-authjs-nextjs-email-2fa-example
-
Install dependencies:
npm install
-
Set up your environment variables in
.env
:# Auth.js NEXTAUTH_URL=http://localhost:3000 NEXTAUTH_SECRET=[your-secret] # NotificationAPI credentials NOTIFICATIONAPI_CLIENT_ID=[your-client-id] NOTIFICATIONAPI_CLIENT_SECRET=[your-client-secret]
-
Set up your database:
npx prisma db push
-
Configure NotificationAPI:
- Create an account at NotificationAPI
- Create a "2fa_code" template with the following merge tag:
{{code}}
: The 2FA verification code
-
Run the development server:
npm run dev
app/api/auth/[...nextauth]/route.ts
: Auth.js configuration with 2FA implementationapp/auth/signin/page.tsx
: Sign-in pageprisma/schema.prisma
: Database schema with 2FA fields
MIT