Developer Quick-Start: Build a production-ready Node.js application with Express to send SMS via Vonage API and track delivery status through webhooks. Includes validation, error handling, and real-time DLR processing. 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.
This guide provides a step-by-step walkthrough for building a Node.js application using Express to send SMS messages via the Vonage SMS API and receive real-time delivery status updates through webhooks.
By the end of this tutorial, you'll have built a functional application capable of:
- Sending SMS messages programmatically.
- Receiving and processing delivery status updates (Delivery Receipts or DLRs) from Vonage.
- Handling configuration, security, and error logging.
You'll solve the common need for applications to confirm whether SMS notifications were successfully delivered to the recipient's handset – crucial for reliable communication workflows.1
Technologies Used
- Node.js: A JavaScript runtime environment for building server-side applications.
- Express.js: A minimal and flexible Node.js web application framework for creating API endpoints and handling webhooks.
- Vonage SMS API: Enables sending and receiving SMS messages globally. You'll use the @vonage/server-sdk Node.js library.
- dotenv: A module to load environment variables from a .env file into process.env.
- ngrok: A tool to expose local development servers to the internet, necessary for testing webhooks.
- nodemon (Optional): A utility that monitors changes in your source and automatically restarts your server during development.
- express-validator: Middleware for request validation.
System Architecture
The basic flow of your application works as follows:
- Sending: An API client (e.g., Postman, another service) makes a POST request to your application's /send-sms endpoint.
- Your Express application receives the request, validates it, and uses the Vonage SDK to send the SMS message via the Vonage API.
- Vonage delivers the SMS to the recipient's carrier network.
- Receiving Delivery Receipt: Once the final status of the message is known (e.g., delivered, failed, expired), Vonage sends a POST request (webhook) containing the delivery status information to a predefined endpoint in your application (/delivery-receipt).
- Your Express application receives the webhook, parses the status, and logs it (in a real-world scenario, you'd likely update a database record).
+-------------+ +------------------------+ +----------------+ +-----------------+
| API Client |------>| Your Node.js/Express App |------>| Vonage API |------>| Recipient Phone |
| (Postman) | (1) | (localhost:3000) | (2) | (sms.nexmo.com)| (3) | |
+-------------+ +------------------------+ +----------------+ +-----------------+
^ | |
| (5) Webhook POST /delivery-receipt | (4) Delivery Status |
+--------------------------------------+----------------------+
(via ngrok tunnel)
Prerequisites
- Node.js and npm (or yarn): Installed on your system. (Download Node.js)
- Vonage API Account: Sign up for free at Vonage API Dashboard.
- Vonage API Key and Secret: Found on the main page of your Vonage Dashboard after signing in.
- Vonage Virtual Number: You need a Vonage phone number capable of sending SMS. You can purchase one from the dashboard: Numbers > Buy Numbers.
- ngrok: Installed and authenticated. (Download ngrok)
- Basic understanding of JavaScript, Node.js, Express, and REST APIs.
1. Setting Up the Project
Initialize your Node.js project and install the necessary dependencies.
- Create Project Directory: Open your terminal and create a new directory for your project, then navigate into it.
mkdir vonage-sms-dlr-guide
cd vonage-sms-dlr-guide
- Initialize Node.js Project: Initialize the project using npm, accepting the defaults.
npm init -y
This creates a package.json file.
- Enable ES Modules: Since you'll use ES Module
importsyntax (e.g.,import express from 'express'), tell Node.js to treat.jsfiles as modules. Open yourpackage.jsonfile and add the line"type": "module"at the top level:
{
"name": "vonage-sms-dlr-guide",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
- Install Dependencies: Install Express for the web server, the Vonage Server SDK for interacting with the API, dotenv for managing environment variables, express-validator for input validation, and optionally nodemon for development convenience.
npm install express @vonage/server-sdk dotenv express-validator
npm install --save-dev nodemon
- Configure
nodemon(Optional): If you installednodemon, add a development script to yourpackage.json. Openpackage.jsonand add/modify thescriptssection:
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
This allows you to run npm run dev to start your server with auto-reloading on file changes.
- Create Core Files: Create the main application file and files for environment variables and ignored files.
touch index.js .env .gitignore
- Configure
.gitignore: Prevent sensitive information and unnecessary files from being committed to version control. Add the following to your.gitignorefile:
# .gitignore
node_modules
.env
npm-debug.log
*.log
- Configure
.env: Add placeholders for your Vonage credentials and number. You'll also add aBASE_URLwhich will be your ngrok URL later. Don't commit this file to Git.
.env
# .env
VONAGE_API_KEY=YOUR_API_KEY
VONAGE_API_SECRET=YOUR_API_SECRET
VONAGE_NUMBER=YOUR_VONAGE_VIRTUAL_NUMBER
PORT=3000
BASE_URL=http://localhost:3000 # Replace with ngrok URL during testing
- VONAGE\_API\_KEY: Your API key from the Vonage Dashboard.
- VONAGE\_API\_SECRET: Your API secret from the Vonage Dashboard.
- VONAGE\_NUMBER: The Vonage virtual number you purchased (in E.164 format, e.g., +14155550100).
- PORT: The port your Express server will listen on.
- BASE\_URL: The public-facing base URL of your application. Crucial for webhook configuration.
2. Implementing Core Functionality: Sending SMS
Write the code to initialize Express and the Vonage SDK, and create an endpoint to send an SMS message.
import express from 'express';
import dotenv from 'dotenv';
import { Vonage } from '@vonage/server-sdk';
dotenv.config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
if (!process.env.VONAGE_API_KEY || !process.env.VONAGE_API_SECRET || !process.env.VONAGE_NUMBER) {
console.error('Error: Missing Vonage API credentials or number in .env file.');
process.exit(1);
}
const vonage = new Vonage({
apiKey: process.env.VONAGE_API_KEY,
apiSecret: process.env.VONAGE_API_SECRET,
});
app.post('/send-sms', async (req, res) => {
const { to, text } = req.body;
if (!to || !text) {
return res.status(400).json({ error: 'Missing "to" or "text" field in request body.' });
}
if (!/^\+?\d{10,15}$/.test(to)) {
return res.status(400).json({ error: '"to" field must be a valid phone number, preferably in E.164 format (e.g., +14155550100).' });
}
console.log(`Attempting to send SMS to: ${to}`);
try {
const resp = await vonage.sms.send({
to: to,
from: process.env.VONAGE_NUMBER,
text: text,
});
console.log('Message submission response:', resp);
if (resp.messages[0].status === '0') {
res.status(200).json({
message: 'SMS submitted successfully!',
messageId: resp.messages[0]['message-id']
});
} else {
console.error(`Message submission failed with error: ${resp.messages[0]['error-text']}`);
res.status(400).json({
error: `Message submission failed: ${resp.messages[0]['error-text']}`,
errorCode: resp.messages[0].status
});
}
} catch (error) {
console.error('Error sending SMS via Vonage API:', error);
let errorMessage = 'Failed to send SMS due to a server or network error.';
if (error.response && error.response.data) {
console.error('Vonage API Error Details:', error.response.data);
errorMessage = error.response.data.title || error.response.data.detail || errorMessage;
}
res.status(500).json({ error: errorMessage, details: error.message });
}
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
if (process.env.BASE_URL && process.env.BASE_URL.includes('localhost')) {
console.warn('Reminder: Your BASE_URL in .env is set to localhost. You\'ll need to update it with your ngrok URL and configure Vonage webhooks for delivery receipts to work.');
}
});
process.on('SIGINT', () => {
console.log('Received SIGINT. Shutting down gracefully…');
process.exit(0);
});
Explanation:
- Imports: Import express, dotenv, and Vonage from @vonage/server-sdk.
- Environment Variables: dotenv.config() loads variables from .env. Add a check to ensure critical Vonage variables are present.
- Express Setup: Initialize Express and use middleware (express.json, express.urlencoded) to easily parse incoming request bodies.
- Vonage Initialization: Create a Vonage client instance using the API key and secret from your environment variables.
/send-smsEndpoint:
- Defines a POST route at /send-sms.
- Extracts the recipient number (to) and message content (text) from the request body.
- Performs basic validation (improved later) to ensure to and text are provided and to looks somewhat like a phone number (clarifying E.164 format is preferred).
- Uses vonage.sms.send() within an async function to send the message. This method requires to, from (your Vonage number), and text.
- Important: The response from vonage.sms.send() confirms submission to Vonage, not final delivery. It includes a status code ('0' means success) and the message-id. Check this status for immediate feedback.
- Includes try...catch for handling network or API-level errors during the call. It logs errors and returns appropriate status codes (400 for submission errors, 500 for server errors).
- Server Start: The server starts listening on the port defined in .env (or default 3000). A warning reminds you about ngrok if the BASE\_URL hasn't been updated.
- Graceful Shutdown: Handles SIGINT (Ctrl+C) for a cleaner shutdown process.
3. Handling Delivery Status Callbacks (Webhooks)
Vonage uses webhooks to send Delivery Receipts (DLRs) back to your application. We need an endpoint to receive these POST requests.
- Set up
ngrok: Open a new terminal window and runngrokto expose your local server running on port 3000.
ngrok http 3000
ngrok will display forwarding URLs (e.g.,
https://<random-string>.ngrok-free.app). Copy the https URL. This is your
public URL.
- Update
.env: Replace theBASE_URLin your.envfile with thehttpsURL provided by ngrok.
.env
# .env
# ... other variables ...
BASE_URL=https://<random-string>.ngrok-free.app
Restart your Node.js application (npm run dev or npm start) for
the changes in .env to take effect.
- Configure Vonage Webhooks:
- Go to your Vonage API Dashboard.
- Navigate to Settings in the left-hand menu.
- Find the API settings section (you might need to scroll down).
- In the SMS Settings card, ensure "SMS API" is selected.
- In the Delivery receipts (DLR) field under "Webhook URL for DLR", enter your full ngrok webhook URL: YOUR\_NGROK\_HTTPS\_URL/delivery-receipt (e.g., https://<random-string>.ngrok-free.app/delivery-receipt).
- Set the HTTP Method to POST.
- Click Save changes.
- Note: This guide focuses on the SMS API's specific DLR format. Vonage also offers a newer Messages API which uses a different endpoint (/webhooks/dlr) and provides a unified webhook format for multiple channels (SMS, WhatsApp, etc.). For new implementations, you might consider using the Messages API instead, although its setup is slightly different.
- Implement the Webhook Endpoint: Add the following route handler to your
index.jsfile, typically before theapp.listencall.
app.post('/delivery-receipt', (req, res) => {
const params = req.body;
console.log('--- Delivery Receipt Received ---');
console.log(JSON.stringify(params, null, 2));
const messageId = params['message-id'] || params.messageId;
const status = params.status;
const recipient = params.msisdn;
if (!messageId || !status || !recipient) {
console.warn('Received incomplete DLR:', params);
return res.status(200).send('OK');
}
const errorCode = params['err-code'] || params.errCode;
const price = params.price;
const timestamp = params.scts;
const networkCode = params['network-code'] || params.networkCode;
console.log(`DLR Info: Recipient=${recipient}, Message ID=${messageId}, Status=${status}, ErrorCode=${errorCode || 'N/A'}, Timestamp=${timestamp}`);
if (status === 'delivered') {
console.log(`Message ${messageId} successfully delivered to ${recipient}.`);
} else if (status === 'failed' || status === 'rejected') {
console.error(`Message ${messageId} to ${recipient} failed with status: ${status}, error code: ${errorCode}. Check Vonage docs for details.`);
} else {
console.log(`Message ${messageId} to ${recipient} has status: ${status}.`);
}
res.status(200).send('OK');
});
Explanation:
- Route Definition: We define a POST route at /delivery-receipt, matching the URL configured in the Vonage dashboard.
- Parsing: We access the incoming webhook data from req.body. Express's json() and urlencoded() middleware handle parsing based on the Content-Type header sent by Vonage.
- Logging: The raw DLR payload is logged for inspection. Key fields like message-id, status, err-code, msisdn (recipient), and scts (timestamp) are extracted and logged. Note that field names might vary slightly (e.g., message-id vs messageId), so we check for both common variants.
- Business Logic Placeholder: A TODO comment highlights where you would integrate this data into your application's logic (e.g., database updates).
- Status Handling: Basic examples show how to check for specific statuses like delivered or failed.
- Crucial Response: We always send a 200 OK response back to Vonage using res.status(200).send('OK'). This acknowledges receipt of the webhook. If Vonage doesn't receive a 200 OK, it will assume the webhook failed and may retry sending it.
4. Building a Complete API Layer
Let's refine the /send-sms endpoint with robust validation using express-validator.
- Update
/send-smswith Validation: Modify the/send-smsendpoint definition inindex.js.
import express from 'express';
import dotenv from 'dotenv';
import { Vonage } from '@vonage/server-sdk';
import { body, validationResult } from 'express-validator';
const sendSmsValidationRules = [
body('to')
.notEmpty().withMessage('Recipient phone number (""to"") is required.')
.isMobilePhone('any', { strictMode: false }).withMessage('Invalid phone number format for ""to"" field. Recommended format is E.164 (e.g., +14155550100).'),
body('text')
.notEmpty().withMessage('Message text (""text"") is required.')
.isLength({ min: 1, max: 1600 }).withMessage('Message text must be between 1 and 1600 characters.'),
];
const validateRequest = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.warn('Validation Errors:', errors.array());
return res.status(400).json({ errors: errors.array() });
}
next();
};
app.post('/send-sms', sendSmsValidationRules, validateRequest, async (req, res) => {
const { to, text } = req.body;
console.log(`Attempting to send SMS to: ${to}`);
try {
const resp = await vonage.sms.send({
to: to,
from: process.env.VONAGE_NUMBER,
text: text,
});
console.log('Message submission response:', resp);
if (resp.messages[0].status === '0') {
res.status(200).json({
message: 'SMS submitted successfully!',
messageId: resp.messages[0]['message-id']
});
} else {
console.error(`Message submission failed with error: ${resp.messages[0]['error-text']}`);
res.status(400).json({
error: `Message submission failed: ${resp.messages[0]['error-text']}`,
errorCode: resp.messages[0].status
});
}
} catch (error) {
console.error('Error sending SMS via Vonage API:', error);
let errorMessage = 'Failed to send SMS due to a server or network error.';
if (error.response && error.response.data) {
console.error('Vonage API Error Details:', error.response.data);
errorMessage = error.response.data.title || error.response.data.detail || errorMessage;
}
res.status(500).json({ error: errorMessage, details: error.message });
}
});
Changes:
- Imported body and validationResult from express-validator.
- Defined sendSmsValidationRules array specifying rules for to and text. We use isMobilePhone for general validation but message guides towards E.164. Added length constraints for text.
- Created a validateRequest middleware function to check validationResult and return errors if any.
- Added the rules array and the validation middleware to the app.post('/send-sms', ...) definition before the main async handler.
- Removed the initial, basic validation from the main handler as express-validator now handles it more robustly.
- Error handling logic remains similar, checking the direct response status from vonage.sms.send and catching broader API/network errors.
- API Testing Examples (
curl):
- Send SMS (Success): Replace placeholders with your actual recipient number (use E.164
format like
+14155550100).
curl -X POST http://localhost:3000/send-sms \
-H ""Content-Type: application/json"" \
-d '{
""to"": ""+14155550100"",
""text"": ""Hello from Vonage and Node.js! This is a test with validation.""
}'
Expected Response (200 OK):
{
""message"": ""SMS submitted successfully!"",
""messageId"": ""some-message-id-from-vonage""
}
- Send SMS (Validation Error - Missing 'text'):
curl -X POST http://localhost:3000/send-sms \
-H ""Content-Type: application/json"" \
-d '{
""to"": ""+14155550100""
}'
Expected Response (400 Bad Request):
{
""errors"": [
{
""type"": ""field"",
""msg"": ""Message text (\""text\"") is required."",
""path"": ""text"",
""location"": ""body""
},
{
""type"": ""field"",
""value"": """",
""msg"": ""Message text must be between 1 and 1600 characters."",
""path"": ""text"",
""location"": ""body""
}
]
}
- Send SMS (Validation Error - Invalid 'to'):
curl -X POST http://localhost:3000/send-sms \
-H ""Content-Type: application/json"" \
-d '{
""to"": ""invalid-number"",
""text"": ""Testing invalid number""
}'
Expected Response (400 Bad Request):
{
""errors"": [
{
""type"": ""field"",
""value"": ""invalid-number"",
""msg"": ""Invalid phone number format for \""to\"" field. Recommended format is E.164 (e.g., +14155550100)."",
""path"": ""to"",
""location"": ""body""
}
]
}
- Delivery Receipt Webhook (Simulated): You can't easily simulate the exact Vonage
DLR POST with
curlwithout knowing a validmessage-idbeforehand, but you can test if your endpoint receives a POST correctly. Use the ngrok inspector (http://127.0.0.1:4040in your browser) to see the real DLRs coming from Vonage after sending a message.
5. Integrating with Vonage Services (Recap & Details)
Let's consolidate the key integration points with Vonage.
- API Credentials:
- How to Obtain: Log in to the Vonage API Dashboard. Your API Key and API Secret are displayed prominently on the main page ("API key" and "Secret").
- Secure Storage: Store these values in your .env file (VONAGE\_API\_KEY, VONAGE\_API\_SECRET) and ensure .env is listed in your .gitignore. Never hardcode credentials directly in your source code.
- Purpose: Used by the @vonage/server-sdk to authenticate your API requests.
- Virtual Number:
- How to Obtain: In the dashboard, navigate to Numbers > Buy Numbers. Search for numbers by country and features (ensure SMS is selected). Purchase a number. Alternatively, use the Vonage CLI (vonage numbers:search GB --features=SMS, vonage numbers:buy <number> GB).
- Secure Storage: Store the purchased number (in E.164 format, e.g., +14155550100) in your .env file (VONAGE\_NUMBER).
- Purpose: Acts as the 'sender ID' for your outgoing SMS messages in many regions (required in the US/Canada).
- Webhook Configuration (Delivery Receipts):
- How to Configure: Dashboard > Settings > API settings > SMS Settings card.
- URL: Set the "Delivery receipts (DLR)" URL to YOUR\_NGROK\_HTTPS\_URL/delivery-receipt. Must be publicly accessible (hence ngrok).
- Method: Set to POST.
- Purpose: Tells Vonage where to send the delivery status updates for messages sent using your API key via the SMS API.
- Environment Variable (
BASE_URL): Storing the ngrok URL (or your production URL) in .env (BASE\_URL) helps manage this, although it's primarily used here for the reminder log message. The critical part is pasting the correct URL into the Vonage dashboard.
6. Error Handling, Logging, and Retry Mechanisms
- Error Handling Strategy:
- API Calls (
/send-sms): Use try...catch blocks around vonage.sms.send(). Check the direct response status (resp.messages[0].status). Log detailed errors (console.error). Check error.response.data for specific Vonage API error details if available during exceptions. Return appropriate HTTP status codes (400 for validation/submission errors, 500 for server/API errors) with clear JSON error messages. - Webhooks (
/delivery-receipt): Log incoming DLRs. Use try...catch around your internal processing logic (e.g., database updates). Crucially, always return200 OKto Vonage, even if your internal processing fails, to prevent retries. Log internal processing errors separately. - Logging:
- Use console.log for informational messages (sending attempts, DLR received, status updates).
- Use console.warn for non-critical issues (e.g., validation errors, incomplete DLRs).
- Use console.error for actual errors (API call failures, submission failures, internal processing failures).
- Production: Replace console.\* with a structured logger like Pino or Winston. This allows for log levels, JSON formatting, and easier integration with log management systems.
Bash
- Retry Mechanisms (Vonage):
- Sending: If vonage.sms.send() fails due to a temporary network issue or a 5xx error from Vonage (caught in the catch block), you might implement application-level retries (e.g., using a library like async-retry) with exponential backoff. However, be cautious not to retry on permanent errors (like invalid number format - 4xx errors or submission errors indicated in the response).
- Receiving DLRs: Vonage handles retries automatically if your webhook endpoint doesn't respond with 200 OK within a reasonable timeout (usually several seconds). Your primary responsibility is to ensure your /delivery-receipt endpoint is reliable and responds quickly with 200 OK. Offload heavy processing (like database writes) to happen asynchronously after sending the 200 OK, perhaps using a message queue.
- Common Vonage DLR Statuses/Errors:
- delivered: Successfully delivered to the handset.
- accepted: Accepted by the carrier, awaiting final status.
- failed: Delivery failed (e.g., number invalid, blocked). Check err-code.
- expired: Message validity period expired before delivery.
- rejected: Rejected by Vonage or carrier (e.g., spam filter, permission issue). Check err-code.
- buffered: Temporarily stored, awaiting delivery attempt.
- Refer to the Vonage SMS API Error Codes Documentation for detailed err-code meanings.
7. Database Schema and Data Layer (Conceptual)
While this guide doesn't implement a database, in a production system, you'd need one to track message status.
- Why: To persistently store the
messageIdreceived when sending and associate it with the subsequent delivery status received via webhook. This allows you to query the status of any message sent. - Example Schema (Conceptual - e.g., PostgreSQL):
CREATE TABLE sms_messages (
id SERIAL PRIMARY KEY,
vonage_message_id VARCHAR(50) UNIQUE NOT NULL,
recipient_number VARCHAR(20) NOT NULL,
sender_number VARCHAR(20) NOT NULL,
message_text TEXT,
status VARCHAR(20) DEFAULT 'submitted',
vonage_status_code VARCHAR(10),
price DECIMAL(10, 5),
network_code VARCHAR(10),
submitted_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
last_updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
dlr_timestamp TIMESTAMP WITH TIME ZONE
);
CREATE INDEX idx_sms_vonage_message_id ON sms_messages (vonage_message_id);
CREATE INDEX idx_sms_status ON sms_messages (status);
- Data Layer Logic:
- On Send (
/send-smssuccess): Insert a new record into sms\_messages with the vonage\_message\_id, recipient, sender, text, and set status to 'submitted'. - On Receive DLR (
/delivery-receipt):
- Find the record in sms\_messages using the vonage\_message\_id from the webhook payload.
- If found, update the status, vonage\_status\_code, price, network\_code, dlr\_timestamp, and last\_updated\_at fields based on the DLR data.
- Handle cases where the messageId might not be found (log an error).
- Implement logic based on the updated status (e.g., trigger notifications for failures).
Conclusion
You have successfully built a Node.js application using Express that can send SMS messages via the Vonage API and receive delivery status updates through webhooks. You've learned how to:
- Set up a Node.js project with necessary dependencies.
- Initialize the Vonage Server SDK.
- Create an API endpoint (/send-sms) to send messages, including input validation.
- Configure ngrok to expose your local server for webhook testing.
- Set up webhook URLs in the Vonage Dashboard.
- Implement a webhook endpoint (/delivery-receipt) to receive and process DLRs.
- Understand basic error handling, logging, and the importance of responding correctly to webhooks.
- Conceptualize how to integrate message tracking with a database.
This foundation allows you to build more complex communication workflows requiring reliable SMS delivery confirmation. Remember to replace placeholder credentials and URLs with your actual values and consider using a structured logger and robust database integration for production environments.
References
Footnotes
- Vonage Developer Documentation. "SMS Delivery Receipts API Guide." Vonage API Documentation. Accessed October 2025. https://developer.vonage.com/en/messaging/sms/guides/delivery-receipts. Explains how delivery receipts work, DLR status messages, and error codes for tracking SMS delivery confirmation. ↩
Use the Vonage Server SDK for Node.js and the /send-sms endpoint created in this tutorial. This
endpoint interacts with the Vonage SMS API to send messages programmatically after receiving the recipient's
number and the message text from a POST request. Remember to configure your Vonage API key and secret in the
.env file.
A Delivery Receipt (DLR) is a status update sent by Vonage to your application after an SMS message is sent. It confirms the delivery status (e.g., delivered, failed, expired) of the message, providing crucial feedback for reliable communication workflows. Vonage uses webhooks to send DLRs, ensuring real-time updates.
Set up a webhook URL in your Vonage API dashboard pointing to a /delivery-receipt endpoint in
your Express app. When Vonage sends the DLR as a POST request containing the delivery status, your Express app
parses and logs it. Don't forget to use ngrok during development to expose the local server for webhook
configuration and testing.
Vonage uses webhooks for DLRs to provide real-time updates asynchronously without your application needing to constantly poll the API. This push-based mechanism allows your application to react immediately to delivery status changes, which is essential for time-sensitive applications.
For new projects, consider using the Messages API for its unified webhook format and support for multiple messaging channels beyond just SMS (e.g., WhatsApp). If working with an existing SMS API implementation, migrating to the Messages API is possible but requires adjusting endpoints and data structures.
You need Node.js and npm (or yarn), a Vonage API account with API Key and Secret, a Vonage virtual number for sending SMS, ngrok for testing webhooks, and some familiarity with JavaScript, Node.js, Express, and REST APIs. The tutorial uses other packages such as dotenv, express-validator, and optionally, nodemon.
Run ngrok http 3000 in a separate terminal to expose your local server. Copy the HTTPS URL
provided by ngrok. Update the BASE_URL in your .env file with this HTTPS URL, and
configure it as your webhook URL for Delivery Receipts in the Vonage API Dashboard. Restart your Node.js app
to apply the changes.
Express-validator is used for input validation, enhancing the robustness of your application. It performs
checks on incoming requests in the /send-sms endpoint, such as ensuring the "to" and "text"
fields are present and correctly formatted before sending the SMS, improving security and data quality.
Use try...catch blocks around vonage.sms.send() to handle potential errors like
network issues or incorrect API credentials. Check the resp.messages[0].status code for immediate
submission issues, error.response.data for detailed error information, and return appropriate
HTTP status codes with error messages.
If vonage.sms.send() fails due to temporary issues (e.g., network, 5xx error from Vonage),
implement application-level retries using libraries like async-retry with exponential backoff. Be
careful not to retry on permanent errors like validation failures or incorrect number formats indicated by 4xx
errors.
Always respond to Vonage DLR webhooks with a 200 OK status, even if internal processing fails.
This prevents Vonage from retrying the webhook and potentially causing duplicate processing. Log any internal
processing errors for debugging after sending the 200 OK.
While this tutorial provides a conceptual schema for a database, it's crucial in production to store
messageId, status, and other relevant data. This allows querying and tracking of
messages. Upon sending, store initial data. On receiving a DLR, update the corresponding record with the
delivery status.
Common DLR statuses include 'delivered', 'accepted', 'failed', 'expired', 'rejected', and 'buffered'. 'delivered' signifies successful delivery, 'failed' indicates issues like invalid numbers, and 'rejected' might relate to spam filters. Consult Vonage's DLR status documentation for complete details and corresponding error codes.
Replace console.* logging with structured loggers like Pino or Winston. These loggers provide
log levels, JSON formatting, and easier integration with log management systems, helping in tracking,
analyzing, and debugging applications more efficiently.
Log in to the Vonage API Dashboard. Your API Key and API Secret are prominently displayed on the main page.
Securely store these credentials in a .env file and never commit them to version control systems
like Git.
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 →