Developer Quick-Start: Complete tutorial for building production-ready SMS marketing campaigns using Node.js, Express.js, and Vonage Messages API. Learn webhook integration, delivery tracking, opt-out compliance, and database setup with step-by-step code examples. 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.
β οΈ CONTENT NOTE: This article's filename suggests MessageBird with Next.js and NextAuth, but the content actually covers Vonage (formerly Nexmo) with Express.js and basic API key authentication. If you're looking for MessageBird-specific or Next.js/NextAuth implementations, please refer to platform-specific documentation.
Learn how to build a production-ready SMS marketing campaign system using Node.js, Express.js, and the Vonage Messages API. This comprehensive guide covers everything from sending bulk SMS messages and tracking delivery status through webhooks to managing contact lists and handling opt-out compliance. You'll implement a complete backend application with database integration using Prisma and PostgreSQL, security best practices, and deployment-ready error handling for programmatic SMS marketing campaigns.
What You'll Build: SMS Marketing Campaign System Overview
Core Features:
This tutorial guides you through creating a backend system with these capabilities:
- Storing contact lists with phone numbers and subscription status
- Creating and managing SMS marketing campaigns
- Sending SMS messages reliably via Vonage Messages API
- Receiving real-time delivery status updates through webhooks
- Handling SMS opt-out requests (STOP keyword) for compliance
Real-World Use Cases:
This SMS marketing system solves common business needs for programmatic SMS communication:
- E-commerce promotional campaigns and flash sales
- Appointment reminders for healthcare and service businesses
- Transaction notifications and order status updates
- Customer engagement and retention campaigns
- Time-sensitive alerts and emergency notifications
Technology Stack:
- Node.js (v18+): JavaScript runtime for building scalable server-side applications
- Express.js: Lightweight web application framework for API endpoints and webhook handling
- Vonage Messages API: Enterprise-grade messaging platform for SMS delivery with detailed delivery receipts
@vonage/server-sdk(v3.24.1): Official Node.js SDK for Vonage API integration- PostgreSQL & Prisma: Production database with modern ORM for contacts, campaigns, and message tracking
dotenv: Secure environment variable managementngrok: Development tool for exposing local webhooks (includes 1 static domain since August 2023)
System Architecture:
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| User / Admin | ---> | Express API | ---> | Vonage Messages | ---> | SMS Network |
| (via API call) | | (Node.js App) | | API | | (Recipient) |
+-----------------+ +-------+---------+ +--------+--------+ +--------+--------+
^ | ^ | ^
| | DB Interaction | | SMS Send | SMS Delivery
| v | v |
+---+-------------+ Webhook Callbacks +-------+---------+
| PostgreSQL DB | <------------------------------| Recipient Phone|
| (Contacts, | (Status, Inbound) +-----------------+
| Campaigns) |
+-----------------+
What You'll Learn:
By completing this tutorial, you'll have a fully functional Node.js SMS marketing application with:
- RESTful API endpoints for contact and campaign management
- Vonage Messages API integration for SMS sending
- Webhook handlers for delivery tracking and inbound messages
- Database schema for persistent data storage
- Security middleware and authentication
Prerequisites:
Before starting this tutorial, ensure you have:
- Node.js and npm (or yarn): Version 18+ recommended (Download Node.js)
- Vonage API Account: Free account at Vonage Dashboard
- Vonage Application & Private Key: Messages API-enabled application (covered in setup)
- Vonage Phone Number: SMS-capable virtual number
- US 10DLC Registration: Required for US SMS traffic (mandatory as of 2024, allow 2-4 weeks for approval)
ngrok: Free tier with static domain (Download ngrok)- JavaScript/Node.js Knowledge: Familiarity with async/await patterns
- Command Line Skills: Basic terminal command experience
- PostgreSQL Database (Optional): Local instance via Docker or hosted service
Important: Create your Vonage API Account, Application, Private Key, and rent a virtual number before starting Section 1 (Project Setup).
1. Setting up the Project
Let's create the project structure and install necessary dependencies.
- Create Project Directory:
mkdir nodejs-vonage-campaigns
cd nodejs-vonage-campaigns
- Initialize Node.js Project:
npm init -y
This creates a package.json file.
- Install Dependencies:
npm install express @vonage/server-sdk dotenv
npm install --save-dev nodemon
- express: Web framework.
- @vonage/server-sdk: Vonage API client.
- dotenv: Loads environment variables.
- nodemon: Development utility to automatically restart the server on file changes.
- Install Database Dependencies (Optional - using Prisma & PostgreSQL):
If you plan to use a database (highly recommended for managing contacts and campaigns):
npm install @prisma/client
npm install --save-dev prisma
- @prisma/client: The Prisma database client.
- prisma: Prisma CLI tool for migrations and generation.
- Initialize Prisma (Optional):
npx prisma init --datasource-provider postgresql
This creates a prisma directory with a schema.prisma file and a .env
file (if one doesn't exist).
- Configure
.envFile:
Create a file named .env in the project root. Prisma might have created one already. Add the
following placeholders. We'll fill these in later. .env
# .env
# Vonage Credentials (Messages API requires Application ID & Private Key)
VONAGE_API_KEY=YOUR_VONAGE_API_KEY
VONAGE_API_SECRET=YOUR_VONAGE_API_SECRET # Note: Messages API primarily uses App ID & Private Key for sending. Key/Secret may be needed for signature verification or other Vonage APIs.
VONAGE_APPLICATION_ID=YOUR_VONAGE_APPLICATION_ID
VONAGE_PRIVATE_KEY_PATH=./private.key # Path relative to project root. See Section 12 for production handling.
VONAGE_NUMBER=YOUR_VONAGE_VIRTUAL_NUMBER # The number you rented (e.g., 14155550100)
# Application Settings
PORT=3000
# Database (if using Prisma/PostgreSQL)
# Example: postgresql://user:password@host:port/database?schema=public
DATABASE_URL="YOUR_POSTGRESQL_CONNECTION_STRING"
# Security (Simple API Key Example)
INTERNAL_API_KEY=YOUR_SECRET_API_KEY_FOR_INTERNAL_USE
Important: Add .env and private.key to your
.gitignore file to avoid committing secrets.
- Create
private.keyPlaceholder:
Create an empty file named private.key in the root. You will download the actual key from Vonage
later and place its contents here. This file path method is used for setup; Section 12 discusses secure key
handling for production.
- Project Structure:
Create the following directory structure:
nodejs-vonage-campaigns/
βββ prisma/ # (If using Prisma)
β βββ schema.prisma
βββ src/
β βββ controllers/ # Request handling logic
β βββ services/ # Business logic (Vonage interaction, DB logic)
β βββ routes/ # API route definitions
β βββ middleware/ # Custom middleware (e.g., authentication)
β βββ utils/ # Helper functions
βββ .env
βββ .gitignore
βββ package.json
βββ package-lock.json
βββ server.js # Main application entry point
βββ private.key # Your Vonage private key file
- src/controllers: Handle incoming HTTP requests, validate input, and call services.
- src/services: Contain the core business logic, interact with external APIs (Vonage), and the database.
- src/routes: Define API endpoints and link them to controllers.
- src/middleware: Functions that run before controllers (e.g., authentication, logging).
- src/utils: Reusable utility functions.
- server.js: Main application entry point.
- private.key: Your Vonage private key file.
- Configure
package.jsonScripts:
Add development scripts to your package.json:
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1",
"prisma:migrate": "npx prisma migrate dev",
"prisma:generate": "npx prisma generate"
}
}
- Create Basic Server (
server.js):
require('dotenv').config();
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/health', (req, res) => {
res.status(200).json({ status: 'OK', timestamp: new Date().toISOString() });
});
app.use((err, req, res, next) => {
console.error('Global Error:', err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
app.listen(PORT, () => {
console.log(`Server listening at http://localhost:${PORT}`);
if (!process.env.VONAGE_APPLICATION_ID || !process.env.VONAGE_PRIVATE_KEY_PATH) {
console.warn('Vonage Application ID or Private Key Path not set in .env');
}
if (!process.env.VONAGE_NUMBER) {
console.warn('Vonage Number not set in .env');
}
});
- Run the Server (Development):
npm run dev
If everything is set up correctly, you should see Server listening at http://localhost:3000. You
can test the health check endpoint: curl http://localhost:3000/health.
2. Implementing Core Functionality (Sending SMS)
Let's integrate the Vonage SDK to send messages.
- Create Vonage Service (
src/services/vonageService.js):
This service will encapsulate all interactions with the Vonage SDK.
const { Vonage } = require('@vonage/server-sdk');
const { Message } = require('@vonage/messages');
const path = require('path');
const fs = require('fs');
if (!process.env.VONAGE_APPLICATION_ID) {
throw new Error("VONAGE_APPLICATION_ID is not set in the environment variables.");
}
if (!process.env.VONAGE_PRIVATE_KEY_PATH) {
throw new Error("VONAGE_PRIVATE_KEY_PATH is not set in the environment variables.");
}
if (!process.env.VONAGE_NUMBER) {
throw new Error("VONAGE_NUMBER is not set in the environment variables.");
}
const privateKeyPath = path.resolve(process.env.VONAGE_PRIVATE_KEY_PATH);
if (!fs.existsSync(privateKeyPath)) {
throw new Error(`Private key file not found at path: ${privateKeyPath}. Please ensure the VONAGE_PRIVATE_KEY_PATH in .env is correct and the file exists.`);
}
const vonage = new Vonage({
applicationId: process.env.VONAGE_APPLICATION_ID,
privateKey: privateKeyPath,
});
const vonageNumber = process.env.VONAGE_NUMBER;
async function sendSms(to, text, clientRef) {
console.log(`Attempting to send SMS to ${to} from ${vonageNumber}`);
try {
const resp = await vonage.messages.send(
new Message({
to: to,
from: vonageNumber,
channel: 'sms',
message_type: 'text',
text: text,
client_ref: clientRef
})
);
console.log(`SMS submitted to Vonage for ${to}. Message UUID: ${resp.messageUuid}`);
return { success: true, messageId: resp.messageUuid };
} catch (error) {
console.error(`Error sending SMS to ${to}:`, error?.response?.data || error.message);
let errorMessage = 'Failed to send SMS.';
if (error?.response?.data?.title) {
errorMessage = `${error.response.data.title}: ${error.response.data.detail || error.message}`;
} else if (error.message) {
errorMessage = error.message;
}
return { success: false, error: errorMessage };
}
}
module.exports = {
sendSms,
};
- Why
MessagesAPI? We use vonage.messages.send which corresponds to the more modern Messages API. It supports multiple channels and provides detailed status webhooks (/webhooks/status), which are crucial for tracking campaign delivery. The older vonage.message.sendSms uses the SMS API, which has different webhook formats and capabilities. - Error Handling: The try...catch block captures errors during the API call. We log detailed errors and return a structured object indicating success or failure. We attempt to parse specific error details from the Vonage response if available.
- Credentials: We initialize the SDK using the Application ID and Private Key path from environment variables, as required by the Messages API. We added checks to ensure these variables and the key file exist.
client_ref: This optional parameter is very useful. You can set it to a unique ID (e.g., campaignId:contactId) to correlate status webhooks back to specific messages in your campaign.
- Test Sending (Manual Trigger):
Let's add a temporary route in server.js to test sending a single SMS. Remember to remove or
secure this later.
const { sendSms } = require('./src/services/vonageService');
app.post('/test-send-sms', async (req, res, next) => {
const { to, text } = req.body;
if (!to || !text) {
return res.status(400).json({ error: "Missing 'to' or 'text' in request body." });
}
if (!/^\+?[1-9]\d{1,14}$/.test(to)) {
return res.status(400).json({ error: "Invalid 'to' phone number format. Use E.164 (e.g., +14155550100)." });
}
try {
const result = await sendSms(to, text, `test-${Date.now()}`);
if (result.success) {
res.status(200).json({ message: 'SMS submitted successfully!', messageId: result.messageId });
} else {
res.status(502).json({ error: 'Failed to send SMS via provider.', details: result.error });
}
} catch (err) {
next(err);
}
});
3. Building a Complete API Layer (Campaigns & Contacts)
We need API endpoints to manage contacts and initiate campaigns.
- Simple In-Memory Store (or Database Service):
For simplicity initially, let's use an in-memory store. Replace this with database interactions (Section 6) for persistence.
const contacts = new Map();
const campaigns = new Map();
let nextContactId = 1;
let nextCampaignId = 1;
async function addContact(phone) {
const id = `c${nextContactId++}`;
const normalizedPhone = phone.startsWith('+') ? phone : `+${phone.replace(/\D/g, '')}`;
const contact = { id, phone: normalizedPhone, status: 'active' };
contacts.set(id, contact);
console.log('Added contact:', contact);
return contact;
}
async function getContact(id) {
return contacts.get(id);
}
async function getAllContacts(statusFilter = null) {
const all = Array.from(contacts.values());
if (statusFilter) {
return all.filter(c => c.status === statusFilter);
}
return all;
}
async function updateContactStatus(phone, status) {
for (const [id, contact] of contacts.entries()) {
if (contact.phone === phone) {
contact.status = status;
console.log(`Updated contact ${id} (${phone}) status to ${status}`);
return contact;
}
}
console.warn(`Contact not found for phone ${phone} to update status.`);
return null;
}
async function createCampaign(name, message, contactIds) {
const id = `cmp${nextCampaignId++}`;
const campaign = {
id,
name,
message,
contactIds: [...contactIds],
status: 'pending',
createdAt: new Date().toISOString(),
results: []
};
campaigns.set(id, campaign);
console.log('Created campaign:', campaign);
return campaign;
}
async function getCampaign(id) {
return campaigns.get(id);
}
async function updateCampaignStatus(id, status) {
const campaign = campaigns.get(id);
if (campaign) {
campaign.status = status;
console.log(`Updated campaign ${id} status to ${status}`);
}
}
async function addCampaignResult(campaignId, result) {
const campaign = campaigns.get(campaignId);
if (campaign) {
campaign.results.push(result);
}
}
module.exports = {
addContact,
getContact,
getAllContacts,
updateContactStatus,
createCampaign,
getCampaign,
updateCampaignStatus,
addCampaignResult
};
- Authentication Middleware (Simple API Key):
Protect our internal endpoints.
const INTERNAL_API_KEY = process.env.INTERNAL_API_KEY;
if (!INTERNAL_API_KEY) {
console.warn('SECURITY WARNING: INTERNAL_API_KEY is not set in .env. API endpoints are currently unprotected. This is highly insecure for production.');
}
function requireApiKey(req, res, next) {
if (!INTERNAL_API_KEY) {
return next();
}
const apiKey = req.headers['x-api-key'];
if (apiKey && apiKey === INTERNAL_API_KEY) {
next();
} else {
console.warn('Blocked request due to missing or invalid API Key.');
res.status(401).json({ error: 'Unauthorized: Invalid or missing API Key.' });
}
}
module.exports = { requireApiKey };
- Contact Controller (
src/controllers/contactController.js):
const dataStore = require('../services/dataStoreService');
async function createContact(req, res, next) {
const { phone } = req.body;
if (!phone) {
return res.status(400).json({ error: "Missing 'phone' in request body." });
}
try {
const contact = await dataStore.addContact(phone);
res.status(201).json(contact);
} catch (err) {
next(err);
}
}
async function listContacts(req, res, next) {
const { status } = req.query;
try {
const contacts = await dataStore.getAllContacts(status);
res.status(200).json(contacts);
} catch (err) {
next(err);
}
}
module.exports = {
createContact,
listContacts
};
- Campaign Controller (
src/controllers/campaignController.js):
This controller will orchestrate fetching contacts and sending messages.
const dataStore = require('../services/dataStoreService');
const vonageService = require('../services/vonageService');
async function processCampaignSending(campaign) {
console.log(`Starting to process campaign: ${campaign.id} (${campaign.name})`);
await dataStore.updateCampaignStatus(campaign.id, 'sending');
let successCount = 0;
let failureCount = 0;
const totalContacts = campaign.contactIds.length;
const delayBetweenMessages = 1100;
for (const contactId of campaign.contactIds) {
const contact = await dataStore.getContact(contactId);
if (!contact || contact.status !== 'active') {
console.warn(`Skipping contact ${contactId} (not found or not active) for campaign ${campaign.id}`);
await dataStore.addCampaignResult(campaign.id, {
contactId,
phone: contact?.phone || 'N/A',
status: 'skipped',
error: contact ? `Contact status: ${contact.status}` : 'Contact not found'
});
failureCount++;
continue;
}
const clientRef = `${campaign.id}:${contact.id}`;
const result = await vonageService.sendSms(contact.phone, campaign.message, clientRef);
await dataStore.addCampaignResult(campaign.id, {
contactId,
phone: contact.phone,
messageId: result.messageId,
status: result.success ? 'submitted' : 'failed',
error: result.error
});
if (result.success) {
successCount++;
} else {
failureCount++;
}
if (campaign.contactIds.indexOf(contactId) < totalContacts - 1) {
console.log(`Waiting ${delayBetweenMessages}ms before next message...`);
await new Promise(resolve => setTimeout(resolve, delayBetweenMessages));
}
}
const finalStatus = failureCount > 0 && successCount === 0 ? 'failed' : 'completed';
await dataStore.updateCampaignStatus(campaign.id, finalStatus);
console.log(`Campaign ${campaign.id} processing finished. Status: ${finalStatus}. Success: ${successCount}, Failed/Skipped: ${failureCount}`);
}
async function createAndSendCampaign(req, res, next) {
const { name, message, contactIds } = req.body;
if (!name || !message || !Array.isArray(contactIds) || contactIds.length === 0) {
return res.status(400).json({ error: 'Missing required fields: name, message, contactIds (must be a non-empty array).' });
}
try {
const campaign = await dataStore.createCampaign(name, message, contactIds);
res.status(202).json({ message: 'Campaign accepted for processing.', campaignId: campaign.id });
setImmediate(() => {
processCampaignSending(campaign).catch(err => {
console.error(`Unhandled error during campaign processing ${campaign.id}:`, err);
dataStore.updateCampaignStatus(campaign.id, 'failed').catch(console.error);
});
});
} catch (err) {
next(err);
}
}
async function getCampaignStatus(req, res, next) {
const { id } = req.params;
try {
const campaign = await dataStore.getCampaign(id);
if (campaign) {
res.status(200).json(campaign);
} else {
res.status(404).json({ error: 'Campaign not found.' });
}
} catch (err) {
next(err);
}
}
module.exports = {
createAndSendCampaign,
getCampaignStatus
};
- Asynchronous Processing: Sending many SMS messages can take time. The createAndSendCampaign function
responds 202 Accepted immediately after creating the campaign record. The actual sending logic in
processCampaignSending is triggered asynchronously using setImmediate. Crucially, for production, replace
setImmediatewith a robust background job queue (like BullMQ with Redis) to handle failures, retries, and concurrency properly. - Rate Limiting: A simple setTimeout delay is added between sending messages to comply with Vonage's default rate limits (often 1 message per second per long code number). Adjust delayBetweenMessages based on your number type and account limits. See Section 11 for more on rate limits.
- Client Reference: We construct a clientRef like campaignId:contactId to uniquely identify each message sent. This is vital for correlating status webhooks later.
- Status Tracking: The campaign status (pending, sending, completed, failed) and individual message results are stored.
- API Routes (
src/routes/contactRoutes.js,src/routes/campaignRoutes.js):
const express = require('express');
const contactController = require('../controllers/contactController');
const { requireApiKey } = require('../middleware/authMiddleware');
const router = express.Router();
router.use(requireApiKey);
router.post('/', contactController.createContact);
router.get('/', contactController.listContacts);
module.exports = router;
const express = require('express');
const campaignController = require('../controllers/campaignController');
const { requireApiKey } = require('../middleware/authMiddleware');
const router = express.Router();
router.use(requireApiKey);
router.post('/', campaignController.createAndSendCampaign);
router.get('/:id', campaignController.getCampaignStatus);
module.exports = router;
- Wire up Routes in
server.js:
Uncomment and add the route wiring in server.js:
const contactRoutes = require('./src/routes/contactRoutes');
const campaignRoutes = require('./src/routes/campaignRoutes');
app.use('/api/contacts', contactRoutes);
app.use('/api/campaigns', campaignRoutes);
- Testing API Endpoints:
Restart your server (npm run dev). Use curl or Postman:
- Add Contact:
curl -X POST http://localhost:3000/api/contacts \
-H "Content-Type: application/json" \
-H "X-API-Key: YOUR_SECRET_API_KEY_FOR_INTERNAL_USE" \
-d '{ "phone": "+12015550123" }'
Add a couple more contacts. Note their IDs (e.g., c1, c2).
- List Contacts:
curl http://localhost:3000/api/contacts \
-H "X-API-Key: YOUR_SECRET_API_KEY_FOR_INTERNAL_USE"
- Create & Send Campaign:
curl -X POST http://localhost:3000/api/campaigns \
-H "Content-Type: application/json" \
-H "X-API-Key: YOUR_SECRET_API_KEY_FOR_INTERNAL_USE" \
-d '{
"name": "Spring Sale Test",
"message": "Hi! Check out our amazing Spring Sale!",
"contactIds": ["c1", "c2"]
}'
Check your server logs β you should see messages about processing the campaign and sending SMS. Check the target phones.
- Get Campaign Status:
curl http://localhost:3000/api/campaigns/cmp1 \
-H "X-API-Key: YOUR_SECRET_API_KEY_FOR_INTERNAL_USE"
4. Integrating Vonage Webhooks for SMS Delivery Tracking
To track delivery status and handle opt-outs, we need to configure Vonage webhooks and create corresponding endpoints in our app.
- Obtain Vonage Credentials & Configure Application:
- API Key & Secret: Find these at the top of your Vonage API Dashboard. Add them to your .env file (VONAGE\_API\_KEY, VONAGE\_API\_SECRET). While the Messages API primarily uses Application ID/Private Key for sending, the Key/Secret might be needed for other API interactions or webhook signature verification depending on the method chosen (though JWT is often preferred with Messages API webhooks).
- Application ID & Private Key: If you haven't already, create a Vonage Application in the dashboard:
- Go to "Your applications" -> "Create a new application".
- Give it a name (e.g., "Node SMS Campaign App").
- Enable "Messages" capability.
- Under Messages, configure the Status URL and Inbound URL. These URLs must be publicly accessible. During development, you'll use ngrok URLs here (e.g., https://YOUR\_NGROK\_SUBDOMAIN.ngrok.io/webhooks/status and https://YOUR\_NGROK\_SUBDOMAIN.ngrok.io/webhooks/inbound).
- Generate a Public/Private Key Pair and download the private.key file. Place its contents into the private.key file in your project root. Do not commit this key.
- Note the Application ID generated for this application. Add it to your .env file (VONAGE\_APPLICATION\_ID).
- Link your Vonage Number(s) to this application under the "Link numbers" section.
- Vonage Number: Ensure you have rented an SMS-capable number and added it to .env (VONAGE\_NUMBER). Make sure this number is linked to the Vonage Application you created.
- Expose Local Server with
ngrok:
If your server is running locally on port 3000:
ngrok http 3000
ngrok will provide a public HTTPS URL (e.g., https://abcdef123456.ngrok.io). Use
this base URL when configuring the webhook URLs in the Vonage dashboard. Remember to update the Vonage
Application settings with the correct ngrok URL each time you restart
ngrok, as the subdomain usually changes on the free tier.
- Create Webhook Controller (
src/controllers/webhookController.js):
This handles incoming POST requests from Vonage.
const dataStore = require('../services/dataStoreService');
const { Vonage } = require('@vonage/server-sdk');
const vonage = new Vonage({
apiKey: process.env.VONAGE_API_KEY,
apiSecret: process.env.VONAGE_API_SECRET,
applicationId: process.env.VONAGE_APPLICATION_ID,
});
async function handleStatusWebhook(req, res, next) {
const status = req.body;
console.log('Received Status Webhook:', JSON.stringify(status, null, 2));
const isValidJwt = true;
if (!isValidJwt) {
console.warn('Invalid JWT received on status webhook.');
return res.status(401).send('Invalid signature');
}
const messageId = status.message_uuid;
const messageStatus = status.status;
const timestamp = status.timestamp;
const clientRef = status.client_ref;
const error = status.error;
if (!clientRef) {
console.warn(`Status webhook received without client_ref. Cannot correlate. Message ID: ${messageId}`);
return res.status(200).send('OK');
}
try {
const [campaignId, contactId] = clientRef.split(':');
if (!campaignId || !contactId) {
console.warn(`Could not parse campaignId/contactId from client_ref: ${clientRef}. Message ID: ${messageId}`);
return res.status(200).send('OK');
}
const campaign = await dataStore.getCampaign(campaignId);
if (campaign && campaign.results) {
const resultIndex = campaign.results.findIndex(r => r.messageId === messageId && r.contactId === contactId);
if (resultIndex !== -1) {
campaign.results[resultIndex].status = messageStatus;
campaign.results[resultIndex].timestamp = timestamp;
if (error) {
campaign.results[resultIndex].error = error;
}
console.log(`Updated status for msg ${messageId} (Campaign: ${campaignId}, Contact: ${contactId}) to: ${messageStatus}`);
} else {
console.warn(`Could not find matching result entry for client_ref: ${clientRef}, messageId: ${messageId}`);
}
} else {
console.warn(`Could not find campaign ${campaignId} referenced by client_ref: ${clientRef}`);
}
res.status(200).send('OK');
} catch (err) {
console.error(`Error processing status webhook for client_ref ${clientRef}:`, err);
res.status(200).send('OK');
}
}
async function handleInboundWebhook(req, res, next) {
const inboundMsg = req.body;
console.log('Received Inbound Webhook:', JSON.stringify(inboundMsg, null, 2));
const isValidJwt = true;
if (!isValidJwt) {
console.warn('Invalid JWT received on inbound webhook.');
return res.status(401).send('Invalid signature');
}
if (inboundMsg.channel !== 'sms' || inboundMsg.message_type !== 'text') {
return res.status(200).send('OK');
}
const fromNumber = inboundMsg.from;
const toNumber = inboundMsg.to;
const text = inboundMsg.text?.trim().toUpperCase();
const messageId = inboundMsg.message_uuid;
try {
if (text === 'STOP') {
console.log(`Processing STOP request from ${fromNumber}`);
const updatedContact = await dataStore.updateContactStatus(fromNumber, 'opted-out');
if (updatedContact) {
console.log(`Contact ${fromNumber} status updated to opted-out.`);
} else {
console.warn(`Received STOP from ${fromNumber}, but contact was not found in the data store.`);
}
}
res.status(200).send('OK');
} catch (err) {
console.error(`Error processing inbound webhook from ${fromNumber}:`, err);
res.status(200).send('OK');
}
}
module.exports = {
handleStatusWebhook,
handleInboundWebhook
};
- JWT Validation: Added placeholders and comments emphasizing the critical need to validate incoming webhooks using JWT or another signature verification method provided by Vonage. This is essential for security. The exact implementation depends on Vonage's current SDK capabilities and recommendations.
- Status Handling: Parses the client\_ref to link the status update back to the specific campaign and contact message result stored earlier. Updates the status (delivered, failed, rejected, etc.) in the data store.
- Inbound Handling: Parses incoming SMS messages. Includes basic opt-out logic by checking for the "STOP" keyword (case-insensitive) and updating the contact's status in the data store.
- Response: Both handlers always respond with 200 OK quickly, even if internal processing fails. This prevents Vonage from retrying the webhook unnecessarily. Errors are logged internally.
- Webhook Routes (
src/routes/webhookRoutes.js):
const express = require('express');
const webhookController = require('../controllers/webhookController');
const router = express.Router();
router.post('/status', webhookController.handleStatusWebhook);
router.post('/inbound', webhookController.handleInboundWebhook);
router.get('/status', (req, res) => res.sendStatus(200));
router.get('/inbound', (req, res) => res.sendStatus(200));
module.exports = router;
- Wire up Webhook Routes in
server.js:
Make sure the webhook routes are correctly required and used in server.js (as shown previously,
uncomment the relevant lines). Ensure they are not placed behind the requireApiKey
middleware if you applied it globally earlier.
const contactRoutes = require('./src/routes/contactRoutes');
const campaignRoutes = require('./src/routes/campaignRoutes');
const webhookRoutes = require('./src/routes/webhookRoutes');
app.use('/api/contacts', contactRoutes);
app.use('/api/campaigns', campaignRoutes);
app.use('/webhooks', webhookRoutes);
- Testing Webhooks:
- Ensure ngrok is running and the Vonage Application webhook URLs are updated.
- Restart your Node.js server (npm run dev).
- Send a campaign using the API (/api/campaigns).
- Watch your server logs. You should see:
- "Attempting to send SMS..." logs from vonageService.
- "Received Status Webhook:" logs in webhookController as messages get delivered or fail. Check if the status is updated correctly in your (in-memory) data store by calling the /api/campaigns/:id endpoint again.
- Send an SMS message containing "STOP" from your test phone to your Vonage number.
- Watch your server logs. You should see:
- "Received Inbound Webhook:" log.
- "Processing STOP request..." log.
- "Contact ... status updated to opted-out." log.
- Verify the contact's status by calling /api/contacts. The contact should now have status: 'opted-out'. Subsequent campaigns should skip this contact.
Next Steps and Production Considerations
This completes the core setup for sending SMS and handling basic status and inbound messages. The next steps would involve replacing the in-memory store with a database, adding more robust error handling, implementing a proper job queue, and preparing for deployment.
Critical Production Requirements:
- Replace in-memory data store with PostgreSQL/Prisma database implementation
- Implement BullMQ or similar job queue for reliable campaign processing
- Add comprehensive error handling and structured logging (Winston/Pino)
- Implement JWT webhook validation for security
- Add rate limiting middleware to prevent API abuse
- Set up monitoring and observability (DataDog, New Relic, or similar)
- Implement proper retry logic with exponential backoff
- Add comprehensive test coverage (unit, integration, E2E)
- Complete TCPA compliance requirements and consent management
- Set up environment-specific configurations (dev/staging/production)
Related SMS Integration Tutorials:
For developers interested in other messaging platforms and frameworks:
- MessageBird SMS integration with Node.js
- Next.js SMS marketing with NextAuth authentication
- Twilio SMS API integration for Node.js
- SMS delivery tracking and webhook handling best practices
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 β