Developer Quick-Start: Learn to build secure SMS 2FA authentication in Next.js 15 using Plivo API and NextAuth.js v5. Complete tutorial with code examples, OTP verification, database setup, and production deployment. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.
Introduction
Implement SMS-based two-factor authentication (2FA) in your Next.js application using Plivo's SMS API and NextAuth.js for session management. This tutorial demonstrates how to build a secure authentication system where users verify their identity through SMS one-time passwords (OTP) after entering their login credentials.
Two-factor authentication significantly strengthens application security by requiring both knowledge-based credentials (email and password) and possession-based verification (mobile device with SMS access). This guide covers Next.js 15 project setup, Plivo SMS integration, NextAuth.js authentication flow customization, OTP generation and verification, user 2FA preference management, and production deployment strategies.
What You'll Build:
Create a production-ready Next.js authentication system with:
- Email and password credential authentication
- Optional SMS-based 2FA that users can enable
- Secure OTP generation and verification flow
- Protected routes requiring 2FA completion
- User profile management for 2FA settings
Technologies & Requirements:
- Next.js: React framework for full-stack web applications (App Router). Next.js 15 (released October 2024) requires Node.js 18.18.0 or higher and supports React 19 RC.
- NextAuth.js (v5/beta): Authentication solution for Next.js, handling sessions, providers, and callbacks. NextAuth.js v5 (also known as Auth.js) requires Next.js 14.0 minimum and is currently in beta (as of January 2025). Official documentation available at authjs.dev.
- Plivo: Communications platform API for sending SMS messages. Pay-as-you-go pricing starting at $0.0035 per message for US (verified January 2025).
- Prisma: Next-generation ORM for database access (example uses PostgreSQL, adaptable to others). Prisma ORM 6.x is the latest version with PostgreSQL 9.6+ support (strongly recommend currently supported versions).
- Node.js: JavaScript runtime environment. Minimum version 18.18.0 required for Next.js 15.
- Tailwind CSS: Utility-first CSS framework (default with create-next-app).
- (Optional) shadcn/ui: UI component library used in examples.
System Architecture:
sequenceDiagram
participant User
participant Browser (Next.js Frontend)
participant NextAuth Middleware
participant NextAuth Callbacks (Server)
participant Database (Prisma)
participant Plivo API
User->>Browser (Next.js Frontend): Enters Email/Password on /login
Browser (Next.js Frontend)->>NextAuth Callbacks (Server): Submits Credentials via Server Action
NextAuth Callbacks (Server)->>Database (Prisma): Verify User & Password
alt User Found & Password Correct & 2FA Disabled
NextAuth Callbacks (Server)->>Database (Prisma): Fetch User Data
NextAuth Callbacks (Server)-->>Browser (Next.js Frontend): Create Session Cookie, Redirect to Dashboard
else User Found & Password Correct & 2FA Enabled
NextAuth Callbacks (Server)->>NextAuth Callbacks (Server): Generate OTP
NextAuth Callbacks (Server)->>Database (Prisma): Store OTP Hash & Expiry for User
NextAuth Callbacks (Server)->>Plivo API: Send OTP SMS to User's Phone
Plivo API-->>User: Delivers SMS with OTP
NextAuth Callbacks (Server)-->>Browser (Next.js Frontend): Redirect to /verify-otp page (with partial/pending state)
User->>Browser (Next.js Frontend): Enters OTP on /verify-otp
Browser (Next.js Frontend)->>NextAuth Callbacks (Server): Submits OTP via Server Action
NextAuth Callbacks (Server)->>Database (Prisma): Fetch Stored OTP Hash for User
NextAuth Callbacks (Server)->>NextAuth Callbacks (Server): Verify Submitted OTP against Stored Hash & Expiry
alt OTP Correct
NextAuth Callbacks (Server)->>Database (Prisma): Clear OTP Hash
NextAuth Callbacks (Server)-->>Browser (Next.js Frontend): Establish Full Session, Redirect to Dashboard
else OTP Incorrect/Expired
NextAuth Callbacks (Server)-->>Browser (Next.js Frontend): Show Error on /verify-otp
end
else Invalid Credentials
NextAuth Callbacks (Server)-->>Browser (Next.js Frontend): Show Error on /login
end
%% Subsequent Requests
Browser (Next.js Frontend)->>NextAuth Middleware: Request Protected Route (e.g., /dashboard)
NextAuth Middleware->>NextAuth Middleware: Check Session Cookie
alt Valid Full Session
NextAuth Middleware-->>Browser (Next.js Frontend): Allow Access
else No/Invalid/Partial Session
NextAuth Middleware-->>Browser (Next.js Frontend): Redirect to /login (or /verify-otp if pending)
end
%% Enable/Disable 2FA (Example on /profile page)
User->>Browser (Next.js Frontend): Clicks Enable/Disable 2FA on /profile
Browser (Next.js Frontend)->>NextAuth Callbacks (Server): Submits Request via Server Action
NextAuth Callbacks (Server)->>Database (Prisma): Update user.twoFactorEnabled flag
NextAuth Callbacks (Server)-->>Browser (Next.js Frontend): Confirm Success/Failure
Prerequisites:
- Node.js 18.18.0 or higher (LTS version recommended) and npm/pnpm/yarn. Verify with node --version.
- A Plivo account with available credits.
- A Plivo phone number capable of sending SMS messages (purchased through the Plivo console). SMS rates start at approximately $0.0035 per message for US destinations.
- A database instance (e.g., PostgreSQL 9.6+, MySQL, SQLite). This guide uses PostgreSQL.
- Basic understanding of Next.js, React, and asynchronous JavaScript.
- (Optional) Familiarity with shadcn/ui for UI components, or adapt examples to your preferred library.
Final Outcome:
A Next.js application where users can:
- Register and log in using email and password.
- Optionally enable SMS-based 2FA on their profile.
- Be prompted for an SMS OTP during login if 2FA is enabled.
- Securely access protected dashboard routes only after successful primary login and OTP verification (if applicable).
Verification Date: All technology versions and requirements verified as of January 2025.
How to Set Up Your Next.js Project with Plivo SMS Authentication
Initialize your Next.js 15 application and install the required dependencies for SMS-based two-factor authentication.
Step 1: Create Your Next.js Application
Open your terminal and create a new Next.js project with TypeScript and Tailwind CSS:
npx create-next-app@latest next-plivo-2fa --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"
cd next-plivo-2fa
This command scaffolds a Next.js application using the App Router architecture, TypeScript for type safety, Tailwind CSS for styling, and ESLint for code quality.
Step 2: Install Required Dependencies for SMS 2FA
Install NextAuth.js, Prisma ORM, Plivo SDK, and authentication utility libraries:
npm install next-auth@beta @auth/prisma-adapter prisma
npm install plivo-node bcrypt zod otp-generator
npm install -D @types/bcrypt @types/otp-generator
Package explanations:
- next-auth@beta: Authentication library for Next.js. Install the beta version for Next.js 14+ and App Router compatibility. NextAuth.js v5 is rebranding as Auth.js (documentation at authjs.dev).
- @auth/prisma-adapter: Connects NextAuth with Prisma database.
- prisma: Database ORM for PostgreSQL, MySQL, or SQLite (Prisma 6.x supports PostgreSQL 9.6+).
- plivo-node: Official Plivo Node.js SDK for SMS messaging.
- bcrypt: Password and OTP hashing library for secure storage.
- zod: Runtime type validation and schema validation.
- otp-generator: Generate secure numeric one-time passwords.
- @types/\*: TypeScript type definitions for development.
Step 3: Initialize Prisma Database
Set up Prisma with PostgreSQL as your database provider:
npx prisma init --datasource-provider postgresql
This command creates:
- prisma/schema.prisma: Database schema definition file.
- .env: Environment configuration file with DATABASE\_URL.
Environment variable details:
- DATABASE\_URL: PostgreSQL connection string for your database. Update with your actual credentials and host information.
- NEXTAUTH\_SECRET: Random secret string for encrypting JWT tokens and session cookies. Critical for authentication security. Generate using openssl rand -base64 32 on Linux/macOS.
- NEXTAUTH\_URL: Your application's canonical URL. Required for NextAuth callback URLs and redirects.
- PLIVO\_AUTH\_ID / PLIVO\_AUTH\_TOKEN: Plivo API credentials from your dashboard. Keep these secure and never commit to version control.
- PLIVO\_PHONE\_NUMBER: Your Plivo SMS-enabled phone number in E.164 format (e.g., +12345678900).
- OTP\_EXPIRY\_MINUTES: OTP validity duration in minutes (default: 5 minutes).
Step 4: Configure Environment Variables for Plivo
Open the .env file and add your database connection string and Plivo API credentials. Obtain
Plivo credentials from your Plivo Console (Dashboard β API Keys & Credentials).
.env
# .env
# Database (Prisma will add this during init - update with your actual connection string)
DATABASE_URL="postgresql://user:password@host:port/database?sslmode=require" # Example for PostgreSQL
# NextAuth Configuration
# Generate a strong secret. This is crucial for security.
# Any sufficiently long, random string will work.
# Example generation command (Linux/macOS with OpenSSL): openssl rand -base64 32
NEXTAUTH_SECRET="YOUR_NEXTAUTH_SECRET"
NEXTAUTH_URL="http://localhost:3000" # Use your production URL in deployment
# Plivo Credentials
PLIVO_AUTH_ID="YOUR_PLIVO_AUTH_ID"
PLIVO_AUTH_TOKEN="YOUR_PLIVO_AUTH_TOKEN"
PLIVO_PHONE_NUMBER="+1##########" # Your Plivo SMS-enabled number in E.164 format
# OTP Settings (Optional - Defaults can be set in code)
OTP_EXPIRY_MINUTES=5 # How long an OTP is valid
Step 5: Define Database Schema for 2FA Authentication
Update prisma/schema.prisma to include NextAuth models and custom fields for SMS two-factor
authentication.
Prisma
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql" // Or your chosen provider
url = env("DATABASE_URL")
}
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? @db.Text
access_token String? @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? @db.Text
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
}
model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
// Custom field to track 2FA verification status within a session
twoFactorVerified Boolean? @default(false)
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
password String? // For Credentials provider
accounts Account[]
sessions Session[]
// Custom Fields for 2FA
phoneNumber String? @unique // Store user's verified phone number for OTP
twoFactorEnabled Boolean @default(false)
twoFactorSecret String? // Store hashed OTP or related secret
twoFactorExpiry DateTime? // Store OTP expiry timestamp
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
Database schema key components:
- Standard NextAuth models: Account, Session, User, and VerificationToken for authentication state management.
- Credentials authentication: Added password field to User model for email/password login.
- 2FA custom fields added to User model:
- phoneNumber: Stores user's verified phone number for SMS OTP delivery (unique constraint).
- twoFactorEnabled: Boolean flag indicating whether SMS 2FA is active for the user account.
- twoFactorSecret: Stores hashed OTP temporarily during verification (never store plain text OTPs).
- twoFactorExpiry: Timestamp for OTP expiration validation.
- Session tracking: Added twoFactorVerified field to Session model to track 2FA completion status per login session.
Step 6: Run Database Migrations
Generate and apply your Prisma database schema:
npx prisma migrate dev --name init
This command performs three operations:
- Generates SQL migration files from your schema.prisma definition.
- Applies the migration to create tables in your PostgreSQL database.
- Generates the Prisma Client with TypeScript types for type-safe database queries.
Step 7: Understand the Project Structure
Your Next.js application structure organizes authentication components as follows:
src/
βββ app/ # Next.js App Router pages and layouts
β βββ api/ # API routes (including NextAuth catch-all)
β βββ (auth)/ # Route group for auth pages (login, register, verify-otp)
β β βββ login/
β β βββ register/
β β βββ verify-otp/
β βββ (protected)/ # Route group for authenticated pages
β β βββ dashboard/
β β βββ layout.tsx # Layout protecting routes in this group
β βββ layout.tsx # Root layout
β βββ page.tsx # Home page
βββ components/ # Reusable UI components
β βββ ui/ # (If using shadcn/ui) Generated components
β βββ auth/ # Authentication specific components
βββ lib/ # Utility functions, constants, Prisma client, etc.
β βββ prisma.ts # Prisma client instance
β βββ actions.ts # Server Actions
β βββ auth.ts # NextAuth configuration (main)
β βββ auth.config.ts # NextAuth configuration (callbacks, pages - used by middleware)
β βββ plivo.ts # Plivo client setup and functions
β βββ utils.ts # General utility functions (e.g., OTP generation)
βββ middleware.ts # Next.js Middleware for route protection
This architecture separates authentication concerns using Next.js App Router route groups:
(auth) for public authentication pages and (protected) for secured application
routes.
How to Configure NextAuth.js with Plivo SMS Integration
Configure NextAuth.js v5 (Auth.js) to handle credential authentication and integrate Plivo for SMS-based OTP delivery.
Configure Prisma Client Singleton
Create a singleton Prisma client instance to prevent connection pool exhaustion in development:
import { PrismaClient } from '@prisma/client';
declare global {
var prisma: PrismaClient | undefined;
}
export const prisma = global.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') {
global.prisma = prisma;
}
Set Up Plivo Client for SMS Delivery
Configure the Plivo SMS client using your API credentials from environment variables:
import * as plivo from 'plivo';
const authId = process.env.PLIVO_AUTH_ID;
const authToken = process.env.PLIVO_AUTH_TOKEN;
const plivoPhoneNumber = process.env.PLIVO_PHONE_NUMBER;
let plivoClient: plivo.Client | null = null;
if (!authId || !authToken || !plivoPhoneNumber) {
if (process.env.NODE_ENV === 'production') {
console.error('Plivo credentials or phone number missing in environment variables. SMS sending will fail.');
} else {
console.warn('Plivo credentials or phone number missing. SMS functionality will be disabled/simulated.');
}
} else {
plivoClient = new plivo.Client(authId, authToken);
}
export const sourcePhoneNumber = plivoPhoneNumber;
export async function sendSms(to: string, text: string) {
if (!plivoClient || !sourcePhoneNumber) {
if (process.env.NODE_ENV !== 'production') {
console.log(`SIMULATING SMS to ${to}: ${text}`);
return Promise.resolve({
message: 'SMS simulated',
messageUuid: ['simulated-uuid-' + Math.random().toString(36).substring(7)],
apiId: 'simulated-api-id'
});
}
console.error('Plivo client not initialized or source number missing. Cannot send SMS.');
throw new Error('SMS service is not configured.');
}
try {
const response = await plivoClient.messages.create(
sourcePhoneNumber,
to,
text
);
console.log('Message sent successfully via Plivo. Message UUID:', response.messageUuid);
return response;
} catch (error) {
console.error('Error sending SMS via Plivo:', error);
throw error;
}
}
Configure NextAuth.js Session and JWT Types
NextAuth.js v5 requires two configuration files: auth.config.ts for middleware and
auth.ts for the main authentication logic.
First, extend the Session and JWT types using TypeScript module augmentation to add custom 2FA properties:
import { DefaultSession } from 'next-auth';
import { JWT as NextAuthJWT } from 'next-auth/jwt';
declare module 'next-auth' {
interface Session {
twoFactorVerified?: boolean;
user: {
id: string;
} & DefaultSession['user'];
}
}
declare module 'next-auth/jwt' {
interface JWT {
twoFactorVerified?: boolean;
id?: string;
}
}
Create NextAuth Configuration for Middleware (auth.config.ts)
This configuration file handles route protection and session checks in Next.js middleware:
import type { NextAuthConfig } from 'next-auth';
import { Session } from 'next-auth';
import { JWT } from 'next-auth/jwt';
export const authConfig = {
pages: {
signIn: '/login',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const session = auth;
const isTwoFactorVerified = session?.twoFactorVerified ?? false;
const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
const isOnVerifyOtp = nextUrl.pathname === '/verify-otp';
if (isOnDashboard) {
if (isLoggedIn) {
if (session.user && !isTwoFactorVerified) {
return Response.redirect(new URL('/verify-otp', nextUrl.origin));
}
return true;
}
return false;
} else if (isOnVerifyOtp) {
return isLoggedIn && !isTwoFactorVerified;
} else if (isLoggedIn) {
if (nextUrl.pathname === '/login' || nextUrl.pathname === '/register') {
if(!isTwoFactorVerified) {
return Response.redirect(new URL('/verify-otp', nextUrl.origin));
}
return Response.redirect(new URL('/dashboard', nextUrl.origin));
}
}
return true;
},
async jwt({ token, user, trigger, session: updateSessionData }) {
if (user) {
token.id = user.id;
token.twoFactorVerified = false;
}
if (trigger === ""update"" && updateSessionData?.twoFactorVerified) {
token.twoFactorVerified = true;
}
return token;
},
async session({ session, token }: { session: Session, token?: JWT }) {
if (token?.id && session.user) {
session.user.id = token.id;
}
if (token?.twoFactorVerified !== undefined) {
session.twoFactorVerified = token.twoFactorVerified;
} else {
session.twoFactorVerified = false;
}
return session;
}
},
providers: [],
session: { strategy: 'jwt' },
} satisfies NextAuthConfig;
Create Main NextAuth Configuration (auth.ts)
Implement the Credentials provider with Plivo SMS integration for OTP delivery:
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { PrismaAdapter } from '@auth/prisma-adapter';
import bcrypt from 'bcrypt';
import { z } from 'zod';
import { prisma } from '@/lib/prisma';
import { authConfig } from './auth.config';
import { sendSms } from './plivo';
import { generateOtp, verifyOtp } from './utils';
import { User } from '@prisma/client';
const LoginSchema = z.object({
email: z.string().email({ message: 'Invalid email format.' }),
password: z.string().min(1, { message: 'Password is required.' }),
});
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
unstable_update
} = NextAuth({
...authConfig,
adapter: PrismaAdapter(prisma),
providers: [
Credentials({
async authorize(credentials) {
try {
const parsedCredentials = LoginSchema.safeParse(credentials);
if (!parsedCredentials.success) {
console.warn(""Credential parsing failed:"", parsedCredentials.error.flatten());
return null;
}
const { email, password } = parsedCredentials.data;
const user = await prisma.user.findUnique({ where: { email } });
if (!user || !user.password) {
return null;
}
const passwordsMatch = await bcrypt.compare(password, user.password);
if (!passwordsMatch) {
return null;
}
if (user.twoFactorEnabled && user.phoneNumber) {
const otp = generateOtp();
const otpExpiry = new Date(Date.now() + (parseInt(process.env.OTP_EXPIRY_MINUTES || '5') * 60 * 1000));
const otpHash = await bcrypt.hash(otp, 10);
await prisma.user.update({
where: { id: user.id },
data: {
twoFactorSecret: otpHash,
twoFactorExpiry: otpExpiry,
},
});
try {
await sendSms(user.phoneNumber, `Your verification code is: ${otp}. It expires in ${process.env.OTP_EXPIRY_MINUTES || 5} minutes.`);
} catch (smsError: any) {
console.error(`Failed to send OTP SMS to ${user.phoneNumber}:`, smsError.message || smsError);
throw new Error(""Failed to send verification code. Please try again later."");
}
return user;
} else {
if(user.twoFactorSecret || user.twoFactorExpiry) {
await prisma.user.update({
where: { id: user.id },
data: { twoFactorSecret: null, twoFactorExpiry: null },
});
}
return user;
}
} catch (error) {
console.error(""Error during authorization:"", error);
if (error instanceof Error && error.message.startsWith(""Failed to send"")) {
throw error;
}
return null;
}
},
}),
],
});
Key authentication flow elements:
- Uses PrismaAdapter to synchronize NextAuth session state with your PostgreSQL database.
- Implements Credentials provider with Zod schema validation for email and password.
- Verifies passwords securely using bcrypt comparison.
- SMS 2FA workflow:
- Checks if user has twoFactorEnabled flag set.
- Generates secure numeric OTP and hashes it with bcrypt before database storage.
- Sends OTP via Plivo SMS API to user's registered phone number.
- Returns user object with twoFactorVerified: false to trigger middleware redirect to verification page.
- Handles SMS delivery errors gracefully with user-friendly error messages.
- For users without 2FA enabled, clears any stale OTP data and proceeds with standard login.
- Uses TypeScript module augmentation for type-safe custom session properties.
Configure Next.js Middleware for Route Protection
Create middleware to protect authenticated routes based on 2FA verification status:
import NextAuth from 'next-auth';
import { authConfig } from '@/lib/auth.config';
const { auth: middleware } = NextAuth(authConfig);
export default middleware;
export const config = {
matcher: [
'/dashboard/:path*',
'/verify-otp',
'/login',
'/register',
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
};
Implement OTP Generation and Verification Utilities
Create utility functions for secure OTP generation and validation against stored hashes:
import otpGenerator from 'otp-generator';
import bcrypt from 'bcrypt';
import { prisma } from './prisma';
export function generateOtp(length: number = 6): string {
return otpGenerator.generate(length, {
upperCaseAlphabets: false,
lowerCaseAlphabets: false,
specialChars: false,
digits: true,
});
}
export async function verifyOtp(userId: string, submittedOtp: string): Promise<boolean> {
try {
const user = await prisma.user.findUnique({
where: { id: userId },
select: { twoFactorSecret: true, twoFactorExpiry: true },
});
if (!user || !user.twoFactorSecret || !user.twoFactorExpiry) {
return false;
}
const isExpired = new Date() > user.twoFactorExpiry;
if (isExpired) {
await prisma.user.update({
where: { id: userId },
data: { twoFactorSecret: null, twoFactorExpiry: null },
});
return false;
}
const isOtpValid = await bcrypt.compare(submittedOtp, user.twoFactorSecret);
if (isOtpValid) {
await prisma.user.update({
where: { id: userId },
data: { twoFactorSecret: null, twoFactorExpiry: null },
});
return true;
} else {
return false;
}
} catch (error) {
console.error(`Error during OTP verification for user ${userId}:`, error);
return false;
}
}
Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)
If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.
curl -X POST https://api.sendsmsnokyc.com/messages \
-H "x-api-key: $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": ["+14155551234"],
"channel": ["sms"],
"body": "Your verification code is 482910"
}'
- Instant onboarding: No KYC paperwork or sales queues β grab an API key and fund with crypto (BTC/USDT) or card.
- Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
- Transparent global pricing: Compare exact per-country termination rates on our live pricing page.
Ship Global SMS in One API Call
Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.
Explore SMSRoute Developers β