Developer Quick-Start: Build a production-ready SMS delivery tracking system using Twilio webhooks, Next.js 15 App Router, NextAuth.js v5, and MongoDB. Complete guide with authentication, status callbacks, and real-time updates. 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.
Track SMS delivery status in real-time using Twilio webhooks, Next.js 15 App Router, and MongoDB. This comprehensive tutorial shows you how to build a production-ready SMS tracking system with authenticated user sessions, secure webhook callbacks, and persistent message logging. Learn to implement Twilio status callbacks with signature validation, handle delivery confirmations, and update message statuses automatically when SMS messages are queued, sent, delivered, or fail.
Building applications that interact with users via SMS often requires knowing whether your messages actually reached their destination. Relying solely on sending a message isn't enough; confirming delivery provides crucial feedback for user experience and system reliability.
This guide details how to build a robust system within a Next.js application to send SMS messages via Twilio and receive real-time delivery status updates using Twilio's webhook callbacks. We'll leverage NextAuth.js for user authentication and session management, and MongoDB for storing message logs and statuses.
By the end of this guide, you will have:
- A Next.js application with user authentication.
- Functionality to send SMS messages via Twilio from authenticated user sessions.
- A database schema to log sent messages and their statuses.
- A secure API endpoint to receive status callbacks from Twilio.
- Logic to update message statuses in your database based on Twilio callbacks.
- A basic UI to demonstrate sending messages and viewing their status.
Technologies Used:
- Next.js 15.5 (App Router): A React framework for building server-rendered and static web applications. We'll use the App Router for modern routing and API handling. Latest stable version with React 19 support and Turbopack improvements.
- NextAuth.js v5 (Auth.js): Handles authentication and session management, ensuring only logged-in users can send messages. Now branded as Auth.js with universal auth() method and App Router-first design.
- Twilio Node.js SDK v5: A communication platform as a service (CPaaS) used for sending SMS and providing status webhooks with built-in webhook validation support.
- MongoDB with Mongoose: A NoSQL database for storing user data and message logs. We use Mongoose as the Object Data Modeling (ODM) library for schema definition and interaction with MongoDB.
- Tailwind CSS: For basic styling.
- Node.js 22.x LTS: The runtime environment. Currently in Active LTS until October 2025, then Maintenance LTS until April 2027.
System Architecture:
+-----------------+ +--------------------+ +-----------------+ +----------------------+ +-----------------+
| User Browser | --> | Next.js Frontend | --> | Next.js API Route | --> | Twilio SMS API | --> | Recipient Phone |
| (Authenticated) | | (Send SMS UI) | | (/api/send-sms) | | | +-----------------+
+-----------------+ +--------------------+ +--------+--------+ +----------+-----------+
| | |
| | Stores Initial | Sends Status Update
| | Message Log | (Webhook POST)
| v v
| +---------+---------+ +--------+-------------+
| | MongoDB | <-- | Next.js API Route |
| | (Message Status) | | (/api/sms-status) |
| +-------------------+ +----------------------+
| ^
| | Verifies Request
| |
+-----------------------------------------------------------------------+
(Session Check)
Prerequisites:
- Node.js (LTS version recommended) and npm/yarn installed.
- A Twilio account with an active phone number capable of sending SMS. Find your Account SID and Auth Token in the Twilio Console.
- A MongoDB database instance (e.g., MongoDB Atlas free tier or local installation) and its connection string.
- Familiarity with JavaScript, React, and Next.js concepts.
- ngrok or a similar tunneling service (primarily for testing webhooks locally before deployment).
1. Project Setup
Let's initialize our Next.js project and install necessary dependencies.
1.1 Create Next.js App
Open your terminal and run:
npx create-next-app@latest sms-status-tracker
Follow the prompts:
- Would you like to use TypeScript? No (This guide uses JavaScript)
- Would you like to use ESLint? Yes
- Would you like to use Tailwind CSS? Yes
- Would you like to use \\src/\
directory?\No (or Yes, adjust paths accordingly) - Would you like to use App Router? (recommended) Yes
- Would you like to customize the default import alias? No
1.2 Navigate and Install Dependencies
cd sms-status-tracker
npm install next-auth @auth/mongodb-adapter mongodb mongoose twilio
- next-auth: Core library for authentication.
- @auth/mongodb-adapter: NextAuth.js adapter for MongoDB.
- mongodb: The native MongoDB driver (required by the adapter).
- mongoose: ODM for interacting with MongoDB more easily (optional but recommended for schema definition).
- twilio: The official Twilio Node.js helper library.
1.3 Configure Environment Variables
Create a file named .env.local in the root of your project. Never commit this file to
version control.
# .env.local
# Twilio Credentials (https://console.twilio.com/)
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here # KEEP THIS SECRET
TWILIO_PHONE_NUMBER=+15551234567 # Your active Twilio phone number
# MongoDB Connection String (e.g., from MongoDB Atlas)
DATABASE_URL=mongodb+srv://<username>:<password>@<cluster-url>/<database-name>?retryWrites=true&w=majority
# NextAuth.js Configuration
# Generate strong secrets: `openssl rand -base64 32`
NEXTAUTH_SECRET=your_super_secret_nextauth_value_here # Required for production
NEXTAUTH_URL=http://localhost:3000 # Development URL, change for production
# Twilio Webhook Security (Use TWILIO_AUTH_TOKEN by default, or generate a specific secret)
# Using AUTH_TOKEN is simpler but less isolated. For higher security, set up specific webhook signing keys in Twilio.
TWILIO_WEBHOOK_SECRET=your_auth_token_here # Or a dedicated webhook signing secret
- Obtaining Credentials:
- TWILIO\_ACCOUNT\_SID and TWILIO\_AUTH\_TOKEN: Found on your main Twilio Console dashboard.
- TWILIO\_PHONE\_NUMBER: One of your active numbers from the Twilio Phone Numbers section.
- DATABASE\_URL: Provided by your MongoDB hosting service (like Atlas) when you create a cluster and user. Ensure the user has read/write permissions to the specified database.
- NEXTAUTH\_SECRET: Generate a strong, unique secret using openssl rand -base64 32 in your terminal.
- NEXTAUTH\_URL: The base URL of your application. Use http://localhost:3000 for local development. Update this when deploying.
- TWILIO\_WEBHOOK\_SECRET: For validating incoming webhook requests. By default, Twilio uses your TWILIO\_AUTH\_TOKEN. You can keep it like that for simplicity or configure specific webhook signing keys in Twilio for enhanced security and use that key here.
1.4 Project Structure
Your initial relevant structure should look like this:
sms-status-tracker/
βββ app/
β βββ api/
β β βββ auth/
β β β βββ [...nextauth]/
β β β βββ route.js # NextAuth.js handler
β β βββ send-sms/
β β β βββ route.js # API to send SMS
β β βββ sms-status/
β β βββ route.js # API to receive Twilio callbacks
β βββ components/
β β βββ Provider.js # Session Provider wrapper
β βββ lib/
β β βββ mongodb.js # MongoDB client promise setup
β β βββ mongoose.js # Mongoose connection setup (optional)
β βββ models/
β β βββ Message.js # Mongoose schema for messages
β βββ dashboard/
β β βββ page.js # Simple UI to send SMS
β βββ auth/ # Optional: Custom auth pages dir
β β βββ signin/
β β β βββ page.js
β β βββ verify-request/
β β βββ page.js
β βββ layout.js # Root layout
β βββ page.js # Home page
βββ .env.local # Environment variables (DO NOT COMMIT)
βββ next.config.js
βββ package.json
βββ tailwind.config.js
We will create the missing files and folders as we proceed.
2. Authentication Setup (NextAuth.js)
We need a basic authentication system so only logged-in users can send messages. We'll use the Email provider for simplicity.
2.1 MongoDB Client Setup
Create app/lib/mongodb.js for managing the MongoDB connection promise, essential for the
adapter.
import { MongoClient } from 'mongodb';
if (!process.env.DATABASE_URL) {
throw new Error('Invalid/Missing environment variable: `DATABASE_URL`');
}
const uri = process.env.DATABASE_URL;
const options = {};
let client;
let clientPromise;
if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export default clientPromise;
2.2 NextAuth.js Configuration
Create the NextAuth.js API route handler at app/api/auth/[...nextauth]/route.js.
import NextAuth from 'next-auth';
import EmailProvider from 'next-auth/providers/email';
import { MongoDBAdapter } from '@auth/mongodb-adapter';
import clientPromise from '@/app/lib/mongodb';
export const authOptions = {
adapter: MongoDBAdapter(clientPromise),
providers: [
EmailProvider({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: process.env.EMAIL_SERVER_PORT,
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD,
},
},
from: process.env.EMAIL_FROM,
}),
],
pages: {
signIn: '/auth/signin',
verifyRequest: '/auth/verify-request',
},
session: {
strategy: 'jwt',
},
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async session({ session, token, user }) {
if (token) {
session.userId = token.sub
}
return session
}
}
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
- Note: You need to configure the EmailProvider with actual email sending credentials (like SendGrid API key, SMTP details) in your .env.local file for magic link emails to work. This setup is shown conceptually; refer to NextAuth.js and your email provider's documentation for details. For this guide's core focus (SMS status), having any working authentication method (Email, Google, Credentials, etc.) is sufficient.
2.3 Session Provider Setup
NextAuth.js requires a <SessionProvider> at the root of your application to manage session
state client-side.
Create app/components/Provider.js:
'use client';
import { SessionProvider } from 'next-auth/react';
const Provider = ({ children, session }) => {
return <SessionProvider session={session}>{children}</SessionProvider>;
};
export default Provider;
Update your root layout app/layout.js:
import './globals.css';
import { Inter } from 'next/font/google';
import Provider from './components/Provider';
const inter = Inter({ subsets: ['latin'] });
export const metadata = {
title: 'SMS Status Tracker',
description: 'Track Twilio SMS delivery status with Next.js',
};
export default function RootLayout({ children }) {
return (
<html lang=""en"">
<body className={inter.className}>
<Provider> {/* Wrap children with the Session Provider */}
{children}
</Provider>
</body>
</html>
);
}
Create simple sign-in/out buttons. Update app/page.js:
'use client';
import { useSession, signIn, signOut } from 'next-auth/react';
import Link from 'next/link';
export default function Home() {
const { data: session, status } = useSession();
return (
<main className=""flex min-h-screen flex-col items-center justify-center p-24"">
<h1 className=""text-4xl font-bold mb-8"">SMS Status Tracker</h1>
{status === 'loading' && <p>Loading...</p>}
{status === 'authenticated' && session && (
<div className=""text-center"">
<p className=""mb-4"">Signed in as {session.user?.email}</p>
<Link
href=""/dashboard""
className=""bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mr-2""
>
Go to Dashboard
</Link>
<button
onClick={() => signOut()}
className=""bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded""
>
Sign Out
</button>
</div>
)}
{status === 'unauthenticated' && (
<button
// Point to the specific provider or the default sign-in page
onClick={() => signIn('email')} // Or just signIn() for default page
className=""bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded""
>
Sign In
</button>
// If using Email provider, you might need an input field here or redirect to pages.signIn
)}
</main>
);
}
Create a basic sign-in page app/auth/signin/page.js if using the pages.signIn
option:
'use client';
import { useState } from 'react';
import { signIn } from 'next-auth/react';
export default function SignIn() {
const [email, setEmail] = useState('');
const handleSignIn = (e) => {
e.preventDefault();
signIn('email', { email, callbackUrl: '/auth/verify-request' });
};
return (
<div className=""flex justify-center items-center min-h-screen"">
<form
onSubmit={handleSignIn}
className=""bg-white p-8 rounded shadow-md w-full max-w-sm""
>
<h2 className=""text-2xl font-bold mb-6 text-center text-gray-800"">Sign In / Sign Up</h2>
<p className=""text-center text-gray-600 mb-6"">
Enter your email to receive a magic link.
</p>
<div className=""mb-4"">
<label htmlFor=""email"" className=""block text-gray-700 text-sm font-bold mb-2"">
Email
</label>
<input
type=""email""
id=""email""
name=""email""
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className=""shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline""
placeholder=""you@example.com""
/>
</div>
<button
type=""submit""
className=""bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline w-full""
>
Send Magic Link
</button>
</form>
</div>
);
}
And a verification request page app/auth/verify-request/page.js:
export default function VerifyRequest() {
return (
<div className=""flex justify-center items-center min-h-screen"">
<div className=""bg-white p-8 rounded shadow-md text-center"">
<h2 className=""text-2xl font-bold mb-4 text-gray-800"">Check your email</h2>
<p className=""text-gray-600"">
A sign in link has been sent to your email address. Click the link to sign in.
</p>
</div>
</div>
);
}
Now you should have a functional authentication flow.
3. Database Schema for Messages
We need a way to store information about the SMS messages we send, including their status.
3.1 Mongoose Connection (Optional but helpful)
Create app/lib/mongoose.js to manage the Mongoose connection.
import mongoose from 'mongoose';
const MONGODB_URI = process.env.DATABASE_URL;
if (!MONGODB_URI) {
throw new Error(
'Please define the DATABASE_URL environment variable inside .env.local'
);
}
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
async function dbConnect() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
return mongoose;
});
}
cached.conn = await cached.promise;
console.log(""Mongoose Connected!"");
return cached.conn;
}
export default dbConnect;
3.2 Message Model
Create the Mongoose schema in app/models/Message.js.
import mongoose from 'mongoose';
const MessageSchema = new mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
to: {
type: String,
required: [true, 'Recipient phone number is required.'],
trim: true,
},
body: {
type: String,
required: [true, 'Message body is required.'],
trim: true,
},
twilioSid: {
type: String,
required: true,
unique: true,
index: true,
},
status: {
type: String,
required: true,
default: 'queued',
enum: ['queued', 'sending', 'sent', 'delivered', 'undelivered', 'failed', 'received'],
},
errorCode: {
type: Number,
required: false,
},
errorMessage: {
type: String,
required: false,
}
},
{
timestamps: true,
}
);
export default mongoose.models.Message || mongoose.model('Message', MessageSchema);
This schema stores essential details: who sent it (userId), the recipient (to), the
content (body), the unique Twilio Message SID (twilioSid) for correlation, the
delivery status, and timestamps. We also added fields for potential error details.
4. Implementing SMS Sending
Let's create the API endpoint and UI to send SMS messages.
4.1 API Route: Send SMS
Create app/api/send-sms/route.js.
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import dbConnect from '@/app/lib/mongoose';
import Message from '@/app/models/Message';
import twilio from 'twilio';
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const twilioPhoneNumber = process.env.TWILIO_PHONE_NUMBER;
const client = twilio(accountSid, authToken);
export async function POST(request) {
const session = await getServerSession(authOptions);
if (!session || !session.userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
let recipient;
let messageBody;
try {
const body = await request.json();
recipient = body.to;
messageBody = body.body;
if (!recipient || typeof recipient !== 'string' || !recipient.trim()) {
return NextResponse.json({ error: 'Recipient phone number (`to`) is required.' }, { status: 400 });
}
if (!messageBody || typeof messageBody !== 'string' || !messageBody.trim()) {
return NextResponse.json({ error: 'Message body (`body`) is required.' }, { status: 400 });
}
if (!/^\+?[1-9]\d{1,14}$/.test(recipient)) {
return NextResponse.json({ error: 'Invalid recipient phone number format.' }, { status: 400 });
}
} catch (error) {
return NextResponse.json({ error: 'Invalid request body.' }, { status: 400 });
}
const statusCallbackUrl = `${process.env.NEXTAUTH_URL}/api/sms-status`;
try {
await dbConnect();
const message = await client.messages.create({
body: messageBody,
from: twilioPhoneNumber,
to: recipient,
statusCallback: statusCallbackUrl,
statusCallbackMethod: 'POST',
});
console.log(`Twilio message sent: SID ${message.sid}, Status: ${message.status}`);
const newMessageLog = new Message({
userId: session.userId,
to: recipient,
body: messageBody,
twilioSid: message.sid,
status: message.status,
});
await newMessageLog.save();
console.log(`Message log created in DB for SID: ${message.sid}`);
return NextResponse.json(
{ success: true, messageSid: message.sid, status: message.status },
{ status: 201 }
);
} catch (error) {
console.error('Error sending SMS or saving log:', error);
const errorMessage = error.message || 'Failed to send SMS.';
let statusCode = 500;
if (error.status) {
statusCode = error.status;
}
try {
await dbConnect();
const failedLog = new Message({
userId: session.userId,
to: recipient,
body: messageBody,
twilioSid: `failed_${Date.now()}`,
status: 'failed',
errorMessage: errorMessage,
errorCode: error.code
});
await failedLog.save();
} catch (dbError) {
console.error(""Failed to save error log to DB:"", dbError);
}
return NextResponse.json({ error: errorMessage, code: error.code }, { status: statusCode });
}
}
Explanation:
- Authentication: Uses getServerSession to ensure only logged-in users can access this endpoint.
- Input Parsing & Validation: Reads the to (recipient phone number) and body (message content) from the request. Includes basic validation.
- Status Callback URL: Constructs the absolute URL pointing to our sms-status API route. Crucially, this must be a publicly accessible URL. For local development, use your ngrok URL. For production, use your deployed application's URL.
- Twilio Interaction: Initializes the Twilio client and calls client.messages.create. We pass the statusCallback URL here.
- Database Logging: Connects to MongoDB using dbConnect and creates a new Message document using the Message model, storing the twilioSid and initial status provided by Twilio.
- Error Handling: Includes try...catch blocks to handle potential errors during Twilio API calls or database operations, returning appropriate error responses. It attempts to log failed attempts as well.
4.2 Frontend UI: Send SMS Form
Create a simple dashboard page at app/dashboard/page.js where users can send messages.
'use client';
import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
export default function Dashboard() {
const { data: session, status } = useSession();
const router = useRouter();
const [recipient, setRecipient] = useState('');
const [messageBody, setMessageBody] = useState('');
const [isSending, setIsSending] = useState(false);
const [feedback, setFeedback] = useState({ type: '', message: '' });
const [messages, setMessages] = useState([]);
useEffect(() => {
if (status === 'unauthenticated') {
router.push('/');
}
}, [status, router]);
const fetchMessages = () => {
console.log(""Fetching messages - API endpoint needed"");
setMessages([
{_id: ""1"", to: ""+1555000111"", body: ""Test message 1"", status: ""delivered"", twilioSid: ""SMxxx1"", createdAt: new Date(Date.now() - 60000 * 5).toISOString()},
{_id: ""2"", to: ""+1555000222"", body: ""Test message 2"", status: ""sent"", twilioSid: ""SMxxx2"", createdAt: new Date(Date.now() - 60000 * 2).toISOString()},
{_id: ""3"", to: ""+1555000333"", body: ""Test message 3"", status: ""failed"", twilioSid: ""SMxxx3"", createdAt: new Date(Date.now() - 60000 * 1).toISOString(), errorMessage: ""Invalid number""},
].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)));
};
useEffect(() => {
if (status === 'authenticated') {
fetchMessages();
}
}, [status]);
const handleSubmit = async (e) => {
e.preventDefault();
if (!recipient || !messageBody) {
setFeedback({ type: 'error', message: 'Please enter recipient and message.' });
return;
}
setIsSending(true);
setFeedback({ type: '', message: '' });
try {
const response = await fetch('/api/send-sms', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ to: recipient, body: messageBody }),
});
const data = await response.json();
if (response.ok) {
setFeedback({ type: 'success', message: `Message sent! SID: ${data.messageSid}, Status: ${data.status}` });
setRecipient('');
setMessageBody('');
fetchMessages();
} else {
setFeedback({ type: 'error', message: `Error: ${data.error || 'Failed to send message.'}` });
}
} catch (error) {
console.error('Send SMS error:', error);
setFeedback({ type: 'error', message: 'An unexpected error occurred.' });
} finally {
setIsSending(false);
}
};
if (status === 'loading') {
return <p className=""text-center mt-10"">Loading session...</p>;
}
if (status === 'unauthenticated') {
return <p className=""text-center mt-10"">Redirecting...</p>;
}
return (
<div className=""container mx-auto p-4 md:p-8"">
<h1 className=""text-3xl font-bold mb-6"">Send SMS</h1>
{feedback.message && (
<div
className={`p-4 mb-4 rounded ${
feedback.type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
}`}
>
{feedback.message}
</div>
)}
<form onSubmit={handleSubmit} className=""bg-white p-6 rounded shadow-md mb-8"">
<div className=""mb-4"">
<label htmlFor=""recipient"" className=""block text-gray-700 text-sm font-bold mb-2"">
Recipient Phone (E.164 format, e.g., +15551234567)
</label>
<input
type=""tel""
id=""recipient""
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
className=""shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline""
placeholder=""+15551234567""
required
/>
</div>
<div className=""mb-6"">
<label htmlFor=""messageBody"" className=""block text-gray-700 text-sm font-bold mb-2"">
Message
</label>
<textarea
id=""messageBody""
value={messageBody}
onChange={(e) => setMessageBody(e.target.value)}
className=""shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline h-24""
placeholder=""Enter your message here""
required
></textarea>
</div>
<div className=""flex items-center justify-between"">
<button
type=""submit""
className=""bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline disabled:opacity-50""
disabled={isSending}
>
{isSending ? 'Sending...' : 'Send Message'}
</button>
</div>
</form>
{/* Display Sent Messages */}
<h2 className=""text-2xl font-bold mb-4"">Message Log (Demo Data)</h2>
<div className=""bg-white p-6 rounded shadow-md"">
{messages.length > 0 ? (
<ul className=""divide-y divide-gray-200"">
{messages.map((msg) => (
<li key={msg._id || msg.twilioSid} className=""py-4"">
<p><strong>To:</strong> {msg.to}</p>
<p><strong>Body:</strong> {msg.body}</p>
<p><strong>Status:</strong> <span className={`font-semibold ${
msg.status === 'delivered' ? 'text-green-600' :
msg.status === 'failed' || msg.status === 'undelivered' ? 'text-red-600' :
'text-yellow-600' // queued, sending, sent
}`}>{msg.status}</span></p>
{msg.errorMessage && <p className=""text-red-500 text-sm""><strong>Error:</strong> {msg.errorMessage} (Code: {msg.errorCode || 'N/A'})</p>}
<p className=""text-xs text-gray-500"">SID: {msg.twilioSid}</p>
<p className=""text-xs text-gray-500"">Sent: {new Date(msg.createdAt).toLocaleString()}</p>
</li>
))}
</ul>
) : (
<p>No message history yet.</p> // Added fallback text
)}
</div>
</div>
);
}
Explanation:
- Form Handling: Includes a form to input recipient number and message body. Validates input and sends a POST request to /api/send-sms.
- Feedback Messages: Displays success or error feedback based on the API response.
- Message Log Display: Shows a list of sent messages (using dummy data for demonstration). In a production app, fetch this from a dedicated API endpoint that queries your database.
5. Receiving Status Callbacks from Twilio
The core feature: receiving updates from Twilio about message delivery status.
5.1 Understanding Twilio Status Callbacks
When you send an SMS via Twilio and include a statusCallback URL, Twilio will send HTTP POST
requests to that URL whenever the message status changes. Possible statuses include:
- queued: Message queued for sending
- sending: Message in process of being sent
- sent: Message sent to the carrier
- delivered: Message successfully delivered to recipient
- undelivered: Message failed to deliver
- failed: Message failed (permanent error)
Security Consideration: The statusCallback URL must be publicly accessible.
Twilio signs all webhook requests with an X-Twilio-Signature header using HMAC-SHA1 and your Auth
Token. You must validate this signature to ensure requests genuinely come from Twilio and haven't been
tampered with.
5.2 API Route: Receive Status Updates
Create app/api/sms-status/route.js to handle incoming Twilio webhooks.
import { NextResponse } from 'next/server';
import twilio from 'twilio';
import dbConnect from '@/app/lib/mongoose';
import Message from '@/app/models/Message';
const authToken = process.env.TWILIO_AUTH_TOKEN;
export async function POST(request) {
const url = new URL(request.url);
const twilioSignature = request.headers.get('x-twilio-signature') || '';
const formData = await request.formData();
const params = {};
for (const [key, value] of formData.entries()) {
params[key] = value;
}
console.log('Received Twilio status callback:', params);
const fullUrl = url.toString();
const isValid = twilio.validateRequest(
authToken,
twilioSignature,
fullUrl,
params
);
if (!isValid) {
console.error('Invalid Twilio signature. Potential security breach.');
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 403 }
);
}
console.log('Twilio signature validated successfully.');
const messageSid = params.MessageSid || params.SmsSid;
const messageStatus = params.MessageStatus || params.SmsStatus;
const errorCode = params.ErrorCode ? parseInt(params.ErrorCode, 10) : null;
const errorMessage = params.ErrorMessage || null;
if (!messageSid || !messageStatus) {
console.error('Missing required parameters in callback.');
return NextResponse.json(
{ error: 'Missing required parameters' },
{ status: 400 }
);
}
try {
await dbConnect();
const updatedMessage = await Message.findOneAndUpdate(
{ twilioSid: messageSid },
{
status: messageStatus,
...(errorCode && { errorCode }),
...(errorMessage && { errorMessage }),
},
{ new: true, runValidators: true }
);
if (!updatedMessage) {
console.warn(`Message with SID ${messageSid} not found in database.`);
return NextResponse.json(
{ message: 'Message not found, but acknowledged' },
{ status: 200 }
);
}
console.log(
`Message ${messageSid} updated to status: ${messageStatus}`
);
return NextResponse.json(
{ success: true, messageSid, newStatus: messageStatus },
{ status: 200 }
);
} catch (error) {
console.error('Error updating message status in database:', error);
return NextResponse.json(
{ message: 'Error logged, but acknowledged' },
{ status: 200 }
);
}
}
Explanation:
- Extract Request Data: Parses the incoming POST request from Twilio (sent as application/x-www-form-urlencoded). Retrieves the X-Twilio-Signature header.
- Signature Validation: Uses twilio.validateRequest() to verify the signature using your Auth Token, the full request URL, and the POST parameters. This is critical for security β it ensures the request genuinely comes from Twilio. According to Twilio's security documentation, this validation uses HMAC-SHA1 with your Auth Token as the secret key.
- Extract Status Information: Retrieves MessageSid (or SmsSid), MessageStatus (or SmsStatus), and optional ErrorCode and ErrorMessage from the callback parameters.
- Database Update: Connects to MongoDB and uses Message.findOneAndUpdate() to find the message by twilioSid and update its status (and error details if present).
- Response to Twilio: Always return HTTP 200 OK to acknowledge receipt. If you return an error, Twilio will retry the webhook multiple times, potentially causing duplicate processing. Even if your database update fails, acknowledge receipt and log the error for later investigation.
Important Note on SSL Termination: If you're deploying behind a load balancer or using a
service that terminates SSL (like Heroku, AWS ELB, or when using ngrok), the URL Twilio uses might be
https:// while your validation code sees http://. This mismatch causes signature
validation to fail. For production deployments, ensure your validation uses the correct protocol, or configure
your infrastructure to pass the original protocol. During local development with ngrok, validation should work
correctly as ngrok provides a public HTTPS URL.
6. Testing the Application Locally
To test webhooks locally, you need a publicly accessible URL since Twilio can't reach localhost.
6.1 Install and Setup ngrok
- Download ngrok: Visit ngrok.com and sign up for a free account. Download and install ngrok.
- Start Your Next.js Application:
npm run dev
Your app should be running on http://localhost:3000.
- Expose localhost with ngrok:
ngrok http 3000
ngrok will provide a public URL like https://abc123def456.ngrok.io.
- Update
NEXTAUTH_URLin.env.local:
NEXTAUTH_URL=https://abc123def456.ngrok.io
Restart your Next.js dev server after changing environment variables.
6.2 Configure Your Email Provider (NextAuth.js)
Ensure your EmailProvider in app/api/auth/[...nextauth]/route.js is configured with
valid SMTP credentials or an email service API key (like SendGrid, Resend, or Nodemailer). Without this, you
won't receive magic link emails for authentication.
6.3 Test the Flow
- Sign In: Navigate to your ngrok URL (https://abc123def456.ngrok.io), click "Sign In", enter your email, and check your inbox for the magic link. Click the link to authenticate.
- Send an SMS: Go to the Dashboard (https://abc123def456.ngrok.io/dashboard), enter a valid recipient phone number (in E.164 format, e.g., +15551234567), type a message, and click "Send Message". You should see a success message with the Twilio Message SID.
- Check Twilio Logs: Open your Twilio Console Messaging Logs to verify the message was sent.
- Monitor Webhook Callbacks: Watch your terminal where your Next.js app is running. You should see console logs like:
Received Twilio status callback: { MessageSid: 'SMxxx...', MessageStatus: 'sent', ... }
Twilio signature validated successfully.
Message SMxxx... updated to status: sent
- Verify Database Updates: Connect to your MongoDB database (e.g., via MongoDB Compass or mongosh) and check the messages collection. The message document should show the updated status field changing from queued to sent to delivered (or failed if there's an error).
6.4 Troubleshooting Webhook Validation
If signature validation fails:
- Check
TWILIO_AUTH_TOKEN: Ensure it's correct and matches your Twilio account. - Verify URL in Logs: Check that the URL being validated matches exactly what Twilio sends (including https:// vs http:// and any query parameters).
- SSL Termination Issues: If using a reverse proxy or load balancer, it might terminate SSL. See Twilio's documentation on handling SSL termination: https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-express-app-by-validating-incoming-twilio-requests
- ngrok URL Changes: ngrok free tier generates a new URL each time you restart it. Update NEXTAUTH\_URL accordingly and restart your app.
7. Deploying to Production
When deploying, ensure the following:
7.1 Environment Variables
Set all environment variables in your hosting platform (Vercel, AWS, Heroku, etc.):
- TWILIO\_ACCOUNT\_SID
- TWILIO\_AUTH\_TOKEN (keep secret)
- TWILIO\_PHONE\_NUMBER
- DATABASE\_URL (MongoDB connection string)
- NEXTAUTH\_SECRET (generate a strong secret)
- NEXTAUTH\_URL (your production domain, e.g., https://yourdomain.com)
- Email provider credentials (EMAIL\_SERVER\_HOST, EMAIL\_SERVER\_PORT, etc.)
7.2 Webhook URL Configuration
Update your statusCallback URL in app/api/send-sms/route.js to use your production
domain:
const statusCallbackUrl = `${process.env.NEXTAUTH_URL}/api/sms-status`;
Since NEXTAUTH_URL is set to your production URL, this will automatically use the correct
callback URL.
7.3 Database Indexes
For production performance, ensure MongoDB indexes are created on frequently queried fields:
twilioSid: {
type: String,
required: true,
unique: true,
index: true,
}
Consider adding a compound index on userId and createdAt for efficient
user-specific message queries:
MessageSchema.index({ userId: 1, createdAt: -1 });
7.4 Rate Limiting and Security
- Rate Limit API Routes: Implement rate limiting on /api/send-sms to prevent abuse. Use packages like express-rate-limit or middleware solutions provided by your hosting platform.
- Input Validation: Enhance phone number validation using libraries like libphonenumber-js to ensure E.164 format compliance.
- CORS Configuration: If building a separate frontend, configure CORS appropriately to allow only your frontend domain.
- Webhook Signature Validation: Never disable webhook signature validation in production. This is your primary defense against unauthorized status updates.
7.5 Monitoring and Logging
- Structured Logging: Replace console.log statements with a proper logging solution (e.g., Winston, Pino, or your platform's logging service).
- Error Tracking: Integrate error tracking tools like Sentry or Rollbar to catch and monitor exceptions in production.
- Webhook Delivery Monitoring: Check Twilio's Webhook Event Logs regularly to ensure callbacks are being delivered successfully. Failed webhooks might indicate issues with your endpoint.
Frequently Asked Questions (FAQ)
How do Twilio SMS status callbacks work?
Twilio SMS status callbacks are HTTP POST requests that Twilio sends to your webhook URL whenever your SMS
message status changes. When you send an SMS with a statusCallback parameter, Twilio tracks the
message through its lifecycle (queued, sending, sent, delivered, or failed) and posts updates to your
endpoint. Each callback includes the MessageSid, current MessageStatus, and optional
error details. Your webhook must return HTTP 200 to acknowledge receipt and prevent retry loops.
How do I validate Twilio webhook signatures in Next.js?
Validate Twilio webhook signatures using the twilio.validateRequest() method from the Twilio
Node.js SDK. This method verifies the X-Twilio-Signature header by computing an HMAC-SHA1 hash of
your full webhook URL and POST parameters using your Auth Token as the secret key. The validation ensures
requests genuinely come from Twilio and haven't been tampered with. Always validate signatures in production
to prevent unauthorized status updates.
What are the possible SMS message status values from Twilio?
Twilio SMS messages progress through these statuses: queued (message queued for sending),
sending (actively being sent), sent (delivered to carrier), delivered
(confirmed delivery to recipient's phone), undelivered (temporary delivery failure), and
failed (permanent delivery failure). Your webhook receives callbacks for each status change,
allowing you to track message progress in real-time and handle delivery failures appropriately.
Why must I return HTTP 200 from Twilio webhooks even on errors?
Always return HTTP 200 OK from Twilio webhooks to acknowledge receipt, even when your database update fails or other errors occur. If you return error status codes (4xx or 5xx), Twilio interprets this as a delivery failure and retries the webhook multiple times, potentially causing duplicate processing. Log errors internally for investigation, but always acknowledge receipt to Twilio to prevent retry loops.
How do I test Twilio webhooks locally with Next.js?
Test Twilio webhooks locally using ngrok to expose your localhost development server with a public HTTPS URL.
Run ngrok http 3000 to create a tunnel, then update your NEXTAUTH_URL environment
variable to the ngrok URL (e.g., https://abc123.ngrok.io). Restart your Next.js dev server and
send test SMS messages. Monitor your terminal for webhook callback logs and verify status updates in your
MongoDB database. ngrok's free tier generates new URLs on each restart.
What Node.js version should I use for Next.js 15 and Twilio?
Use Node.js 22.x LTS (codenamed "Jod") for Next.js 15 and Twilio applications. Node.js 22 is currently in Active LTS until October 2025, then transitions to Maintenance LTS until April 2027. This version provides optimal compatibility with Next.js 15.5, NextAuth.js v5, and the Twilio Node.js SDK. Node.js 18 reaches end-of-life on April 30, 2025, and should not be used for new projects.
How do I handle SSL termination issues with Twilio webhook validation?
SSL termination issues occur when load balancers or reverse proxies terminate HTTPS connections before
reaching your application, causing webhook URL protocol mismatches (Twilio sends to https:// but
your code sees http://). This mismatch fails signature validation. Solutions include configuring
your infrastructure to pass the original protocol header (X-Forwarded-Proto), ensuring your
validation code uses the correct protocol, or in development with ngrok, using the HTTPS URL provided by ngrok
which handles SSL correctly.
8. Conclusion
You've now built a complete SMS delivery tracking system with:
β Authenticated SMS sending using NextAuth.js v5 and Next.js 15 App Router β Real-time status updates via Twilio webhooks with signature validation β Persistent message logging in MongoDB with Mongoose schemas β Secure webhook handling with HMAC-SHA1 signature verification β Production-ready architecture with proper error handling and logging
Key Takeaways
- Always validate webhook signatures β Use twilio.validateRequest() to prevent unauthorized status updates
- Return HTTP 200 to webhooks β Even on errors, to prevent Twilio retry loops
- Use proper Node.js LTS versions β Node.js 22.x is currently in Active LTS (until October 2025)
- Implement comprehensive error handling β Log failures for later investigation while acknowledging receipt
- Test locally with ngrok β Essential for webhook development before production deployment
Next Steps
- Add a real-time UI update mechanism using WebSockets or Server-Sent Events to refresh message statuses without page reload
- Implement message history pagination for users with large message volumes
- Add filtering and search to the message log (by status, date range, recipient)
- Create a message retrieval API endpoint to replace the dummy data in the dashboard
- Implement automated tests for webhook handling and database operations
- Add delivery analytics β track delivery rates, failure reasons, and performance metrics
Additional Resources
- Next.js Documentation: https://nextjs.org/docs
- NextAuth.js (Auth.js) Documentation: https://authjs.dev/
- Twilio Webhooks Security: https://www.twilio.com/docs/usage/webhooks/webhooks-security
- Twilio SMS Status Callbacks: https://www.twilio.com/docs/sms/api/message-resource#message-status-values
- MongoDB Atlas: https://www.mongodb.com/cloud/atlas
- Mongoose Documentation: https://mongoosejs.com/docs/
Source Citations
Node.js & Next.js:
- Node.js LTS Schedule: https://endoflife.date/nodejs
- Node.js 22 LTS Announcement: https://nodesource.com/blog/Node.js-v22-Long-Term-Support-LTS
- Next.js 15 Official Release: https://nextjs.org/blog/next-15
- Next.js 15.5 Release Notes: https://medium.com/@onix\_react/release-next-js-15-5-df0c53e3b79b
Authentication:
- NextAuth.js v5 Migration Guide: https://authjs.dev/getting-started/migrating-to-v5
- Auth.js Official Documentation: https://authjs.dev/
- NextAuth.js with Next.js 15: https://codevoweb.com/how-to-set-up-next-js-15-with-nextauth-v5/
Twilio:
- Twilio Node.js SDK GitHub: https://github.com/twilio/twilio-node
- Twilio Webhook Security Documentation: https://www.twilio.com/docs/usage/webhooks/webhooks-security
- Twilio Webhook Validation in Node.js: https://www.twilio.com/blog/how-to-secure-twilio-webhook-urls-in-nodejs
- Twilio SMS Message Status Values: https://www.twilio.com/docs/sms/api/message-resource#message-status-values
- Twilio Getting Started with Webhooks: https://www.twilio.com/docs/usage/webhooks/getting-started-twilio-webhooks
- Secure Express App with Twilio Validation: https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-express-app-by-validating-incoming-twilio-requests
- Twilio SSL Termination Handling: https://www.twilio.com/en-us/blog/handle-ssl-termination-twilio-node-js-helper-library
- Track Outbound Message Status: https://www.twilio.com/docs/messaging/guides/track-outbound-message-status
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 β