Channel & Routing Summary: Build a Node.js Express application to send SMS and WhatsApp messages using the Vonage Messages API. Includes webhook handling, signature verification, and production security best practices. Looking for unified multi-channel routing with automatic Tier-1 SMS fallback and zero-KYC onboarding? Explore the SMSRoute Messaging API.
Build a Node.js Express application to send SMS and WhatsApp messages via the Vonage Messages API. This guide covers project setup, sending messages through different channels, handling incoming messages and status updates via webhooks, and implementing essential production considerations like security and error handling.
By the end of this tutorial, you'll have a functional application capable of programmatically sending SMS and WhatsApp messages and receiving delivery status updates and inbound messages from users. This provides a foundation for building chatbots, notification systems, two-factor authentication flows, and other communication-driven features.
Project Overview and Goals
What You'll Build:
- A Node.js Express server
- Integration with the Vonage Messages API using the official Node.js SDK
- Functionality to send outbound SMS messages
- Functionality to send outbound WhatsApp messages (using the Vonage Sandbox initially)
- Webhook endpoints to receive inbound messages from users (SMS and WhatsApp)
- Webhook endpoints to receive message status updates (e.g., delivered, failed)
- Secure handling of API credentials and webhook signature verification
Problem Solved:
This application provides a unified way to interact with customers or users over two popular messaging channels β SMS and WhatsApp β directly from your Node.js backend. It abstracts the complexities of the Vonage API into reusable functions and provides a basic structure for handling asynchronous communication events.
Technologies Used:
- Node.js: A JavaScript runtime environment for building server-side applications (Version 18 or higher recommended)
- Express: A minimal and flexible Node.js web application framework used to build the server and API endpoints/webhooks
- Vonage Messages API: A powerful API enabling communication across multiple channels (SMS, MMS, WhatsApp, Facebook Messenger, Viber) through a single interface
- Vonage Node.js Server SDK (
@vonage/server-sdk): Simplifies interaction with Vonage APIs, including authentication and sending messages - Vonage Messages SDK (
@vonage/messages): Provides convenient classes for constructing messages for specific channels (like WhatsAppText) - Vonage JWT SDK (
@vonage/jwt): Used for verifying the signature of incoming webhook requests to ensure they originate from Vonage dotenv: A module to load environment variables from a .env file into process.envngrok: A tool to expose local servers to the internet, necessary for testing webhooks during development
System Architecture:
+-----------------+ HTTP Request +---------------------+ Vonage API Call +-----------------+
| Your Application| ---------------------> | Node.js/Express App | -------------------------> | Vonage Platform |
| (e.g., Frontend)| (API Call) | (Vonage SDK) | (Messages API) | |
+-----------------+ +---------------------+ +-------+---------+
| |
| Webhook Call (POST) | Send Message
V V
+-----------------+ Webhook Call (POST) +-------+---------+ +-------+---------+
| Vonage Platform | <----------------------- | Node.js/Express App | | User's Device |
| | (Inbound Msg / Status) | (Webhook Handler) | | (SMS/WhatsApp) |
+-----------------+ +---------------------+ +-----------------+
Prerequisites:
- Vonage API Account: Sign up for free at Vonage API Dashboard. You get free credit to start.
- Node.js and npm: Install Node.js (v18 or higher recommended, includes npm) from nodejs.org.
- ngrok: Install ngrok from ngrok.com and create a free account to authenticate your agent.
- A Vonage Phone Number: Purchase an SMS-capable virtual number from the Vonage Dashboard (Numbers β Buy numbers).
- WhatsApp Enabled Device: A smartphone with WhatsApp installed for testing.
How Do You Set Up a Node.js Project for Vonage Messaging?
Initialize your Node.js project and install the necessary dependencies.
- Create Project Directory: Open your terminal or command prompt and create a new directory for your project, then navigate into it:
mkdir vonage-node-messaging
cd vonage-node-messaging
- Initialize Node.js Project: Initialize the project using npm. The
-yflag accepts default settings.
npm init -y
This creates a package.json file.
- Install Dependencies: Install Express, the Vonage SDKs, and
dotenv:
npm install express @vonage/server-sdk @vonage/messages @vonage/jwt dotenv
- express: Web framework
- @vonage/server-sdk: Core Vonage SDK for authentication and API calls
- @vonage/messages: Specific classes for constructing message types (e.g., WhatsAppText)
- @vonage/jwt: For webhook signature verification
- dotenv: For managing environment variables
- Create Project Structure: Create a basic structure for your code:
mkdir src
touch src/server.js
touch .env
touch .gitignore
- src/server.js: Your main application code
- .env: Stores sensitive credentials and configuration
- .gitignore: Prevents committing sensitive files (like .env) and node_modules to version control
- Configure
.gitignore: Add the following lines to your.gitignorefile to avoid committing sensitive information and dependencies:
# Dependencies
node_modules/
# Environment Variables
.env
# Vonage Private Key
private.key
# Operating System Files
.DS_Store
Thumbs.db
- Set up Vonage Application: Create a Vonage Application to group your numbers and configurations, and generate authentication credentials.
- Navigate to Applications in your Vonage API Dashboard.
- Click + Create a new application.
- Give your application a name (e.g., "Node Express Messaging").
- Click Generate public and private key. This will automatically download a private.key file. Save this file securely in the root of your project directory (e.g., alongside package.json). Crucially, ensure
private.keyis listed in your.gitignorefile and is NEVER committed to version control. For production, load this key securely (e.g., from environment variables, secrets management, or a secure volume mount) rather than directly from the filesystem. The public key is stored by Vonage. - Enable the Messages capability by toggling it on.
- You'll see fields for Inbound URL and Status URL. Fill these in the next step after starting ngrok. Leave them blank for now or use temporary placeholders like http://localhost.
- Click Generate new application.
- On the next screen, Link the Vonage virtual number you purchased earlier to this application. Find your number and click the "Link" button.
- Note down the Application ID displayed on this page.
- Configure SMS API Settings: Ensure your account uses the Messages API for SMS by default, as recommended by Vonage documentation for new integrations.
- In the Vonage Dashboard, navigate to API Settings.
- Scroll down to the SMS Settings section.
- Under Default SMS Setting, select Messages API.
- Click Save changes.
- Set up WhatsApp Sandbox (for Testing): For testing WhatsApp without a full business setup, use the Vonage Sandbox.
- Navigate to Messages API Sandbox in the Vonage Dashboard.
- Follow the instructions to activate the Sandbox by sending a specific message from your WhatsApp number to the provided Sandbox number. This "allowlists" your number for testing.
- Keep this page open, as you'll need the Sandbox number and will configure webhooks here too.
- Start
ngrok: To receive webhooks from Vonage on your local machine, expose your local server to the internet.
- Open a new terminal window (keep your project terminal open).
- Run
ngrok, specifying the port your Express server will listen on (use port 3000):
ngrok http 3000
ngrokwill display output including a Forwarding URL that looks likehttps://<random-string>.ngrok-free.app(or similar, depending on your plan/version). Copy this HTTPS URL.
- Configure Webhook URLs in Vonage:
- Vonage Application: Go back to your application settings in the Vonage Dashboard (Applications β Your Application Name).
- Enter your ngrok HTTPS URL followed by /webhooks/inbound into the Inbound URL field (e.g., https://<random-string>.ngrok-free.app/webhooks/inbound).
- Enter your ngrok HTTPS URL followed by /webhooks/status into the Status URL field (e.g., https://<random-string>.ngrok-free.app/webhooks/status).
- Click Save changes.
- WhatsApp Sandbox: Go back to the Messages API Sandbox page in the Vonage Dashboard.
- Enter the same URLs (.../webhooks/inbound and .../webhooks/status) into the respective webhook fields on the Sandbox configuration page.
- Click Save webhooks.
- Configure Environment Variables (
.env): Open the.envfile you created and add the following variables, replacing the placeholder values with your actual credentials:
.env
# Vonage API Credentials
VONAGE_API_KEY=YOUR_API_KEY
VONAGE_API_SECRET=YOUR_API_SECRET
# Vonage Application Credentials
VONAGE_APPLICATION_ID=YOUR_APPLICATION_ID
VONAGE_PRIVATE_KEY=./private.key # Path relative to project root β load securely in production!
# Vonage Numbers
VONAGE_SMS_FROM_NUMBER=YOUR_VONAGE_SMS_NUMBER # Your purchased Vonage number in E.164 format (e.g., 14155550100)
VONAGE_WHATSAPP_SANDBOX_NUMBER=14157386102 # The Vonage WhatsApp Sandbox number
# Webhook Security
VONAGE_API_SIGNATURE_SECRET=YOUR_SIGNATURE_SECRET
# Server Configuration
PORT=3000
- VONAGE_API_KEY & VONAGE_API_SECRET: Found at the top of your Vonage API Dashboard.
- VONAGE_APPLICATION_ID: The ID generated when you created the Vonage Application.
- VONAGE_PRIVATE_KEY: The path to the private.key file you downloaded and saved in your project root. Ensure this path is correct relative to where you run the node process.
- VONAGE_SMS_FROM_NUMBER: Your purchased Vonage virtual number (without + or leading 00).
- VONAGE_WHATSAPP_SANDBOX_NUMBER: The specific number provided by the Vonage WhatsApp Sandbox. For production WhatsApp, this would be your registered WhatsApp Business number.
- VONAGE_API_SIGNATURE_SECRET: Found in the Vonage API Dashboard under API Settings β Webhook signature secret. Click "Edit" or "Generate" if needed.
- PORT: The port your Express server will run on (must match the ngrok port).
How Do You Implement SMS and WhatsApp Messaging in Express?
Now, let's write the code in src/server.js to initialize the server, configure Vonage, send messages, and handle webhooks.
require('dotenv').config();
const express = require('express');
const { Vonage } = require('@vonage/server-sdk');
const { WhatsAppText } = require('@vonage/messages');
const { verifySignature } = require('@vonage/jwt');
const app = express();
app.use(express.urlencoded({ extended: true }));
if (!process.env.VONAGE_API_KEY || !process.env.VONAGE_API_SECRET || !process.env.VONAGE_APPLICATION_ID || !process.env.VONAGE_PRIVATE_KEY) {
console.error('ERROR: Missing Vonage API credentials in .env file.');
process.exit(1);
}
if (!process.env.VONAGE_API_SIGNATURE_SECRET) {
console.error('ERROR: Missing VONAGE_API_SIGNATURE_SECRET in .env file. Webhooks cannot be verified.');
process.exit(1);
}
const vonage = new Vonage({
apiKey: process.env.VONAGE_API_KEY,
apiSecret: process.env.VONAGE_API_SECRET,
applicationId: process.env.VONAGE_APPLICATION_ID,
privateKey: process.env.VONAGE_PRIVATE_KEY
},
{
});
async function sendSms(toNumber, messageText) {
console.log(`Attempting to send SMS to ${toNumber}...`);
if (!process.env.VONAGE_SMS_FROM_NUMBER) {
console.error('ERROR: VONAGE_SMS_FROM_NUMBER is not set in .env');
return;
}
try {
const resp = await vonage.messages.send({
message_type: "text",
text: messageText,
to: toNumber,
from: process.env.VONAGE_SMS_FROM_NUMBER,
channel: "sms"
});
console.log(`SMS sent successfully to ${toNumber}. Message UUID: ${resp.messageUuid}`);
} catch (err) {
console.error(`Error sending SMS to ${toNumber}:`, err?.response?.data || err.message);
}
}
async function sendWhatsApp(toNumber, messageText) {
console.log(`Attempting to send WhatsApp message to ${toNumber} via Sandbox...`);
if (!process.env.VONAGE_WHATSAPP_SANDBOX_NUMBER) {
console.error('ERROR: VONAGE_WHATSAPP_SANDBOX_NUMBER is not set in .env');
return;
}
try {
const resp = await vonage.messages.send(
new WhatsAppText({
text: messageText,
to: toNumber,
from: process.env.VONAGE_WHATSAPP_SANDBOX_NUMBER,
})
);
console.log(`WhatsApp message sent successfully to ${toNumber}. Message UUID: ${resp.messageUuid}`);
} catch (err) {
console.error(`Error sending WhatsApp message to ${toNumber}:`, err?.response?.data || err.message);
}
}
function verifyWebhookSignature(req) {
try {
if (!req.rawBody) {
console.error('ERROR: Raw body not available for signature verification. Ensure rawBodyMiddleware is used.');
return false;
}
if (!process.env.VONAGE_API_SIGNATURE_SECRET) {
console.error('ERROR: VONAGE_API_SIGNATURE_SECRET is not set. Cannot verify webhook signature.');
return false;
}
const headers = {};
for (const key in req.headers) {
headers[key.toLowerCase()] = req.headers[key];
}
const token = headers['authorization']?.split(' ')[1];
if (!token) {
console.error('Webhook Error: Authorization header missing or malformed.');
return false;
}
const isValid = verifySignature(token, process.env.VONAGE_API_SIGNATURE_SECRET, req.rawBody.toString());
if (!isValid) {
console.error('Webhook Error: Invalid Signature');
}
return isValid;
} catch (error) {
console.error('Error verifying webhook signature:', error.message);
return false;
}
}
const rawBodyMiddleware = express.raw({
type: 'application/json',
verify: (req, res, buf) => {
req.rawBody = buf;
}
});
app.post('/webhooks/inbound', rawBodyMiddleware, express.json(), async (req, res) => {
console.log('Received Inbound Webhook:');
console.log(JSON.stringify(req.body, null, 2));
if (!verifyWebhookSignature(req)) {
console.log('Webhook signature verification failed. Responding 401.');
return res.status(401).send('Invalid Signature');
}
console.log('Webhook signature verified successfully.');
const { from, channel, message } = req.body;
if (channel === 'sms' || channel === 'whatsapp') {
const sender = from.number || from.id;
const messageContent = message?.content?.text || '[Non-text message content]';
console.log(`Received ${channel.toUpperCase()} message from ${sender}: ""${messageContent}""`);
const replyText = `Thanks for your ${channel.toUpperCase()} message! We received: ""${messageContent}""`;
if (channel === 'sms' && process.env.VONAGE_SMS_FROM_NUMBER) {
if (from.number) {
await sendSms(from.number, replyText);
} else {
console.warn('Cannot reply to SMS: Sender number missing in webhook payload.');
}
} else if (channel === 'whatsapp' && process.env.VONAGE_WHATSAPP_SANDBOX_NUMBER) {
if (from.id) {
await sendWhatsApp(from.id, replyText);
} else {
console.warn('Cannot reply to WhatsApp: Sender ID missing in webhook payload.');
}
}
} else {
console.log(`Received webhook for unhandled channel: ${channel}`);
}
res.status(200).end();
});
app.post('/webhooks/status', rawBodyMiddleware, express.json(), (req, res) => {
console.log('Received Status Webhook:');
console.log(JSON.stringify(req.body, null, 2));
if (!verifyWebhookSignature(req)) {
console.log('Webhook signature verification failed. Responding 401.');
return res.status(401).send('Invalid Signature');
}
console.log('Webhook signature verified successfully.');
const { message_uuid, status, timestamp, error } = req.body;
console.log(`Status update for Message UUID ${message_uuid}: ${status} at ${timestamp}`);
if (error) {
console.error(`Error details: Code=${error.code}, Reason=${error.reason}`);
}
res.status(200).end();
});
app.use(express.json());
app.post('/api/send/sms', async (req, res) => {
const { to, message } = req.body;
if (!to || !message) {
return res.status(400).json({ error: 'Missing ""to"" or ""message"" in request body.' });
}
if (!/^\d{11,15}$/.test(to)) {
return res.status(400).json({ error: 'Invalid ""to"" number format. The Vonage SDK expects E.164 format without the leading \'+\'.' });
}
console.log(`API request to send SMS to ${to}`);
try {
await sendSms(to, message);
res.status(200).json({ status: `SMS dispatch initiated to ${to}` });
} catch (error) {
console.error(""API Error sending SMS:"", error);
res.status(500).json({ error: 'Failed to send SMS.' });
}
});
app.post('/api/send/whatsapp', async (req, res) => {
const { to, message } = req.body;
if (!to || !message) {
return res.status(400).json({ error: 'Missing ""to"" or ""message"" in request body.' });
}
if (!/^\d{11,15}$/.test(to)) {
return res.status(400).json({ error: 'Invalid ""to"" number format. The Vonage SDK expects E.164 format without the leading \'+\'.' });
}
console.log(`API request to send WhatsApp to ${to}`);
try {
await sendWhatsApp(to, message);
res.status(200).json({ status: `WhatsApp dispatch initiated to ${to}` });
} catch (error) {
console.error(""API Error sending WhatsApp:"", error);
res.status(500).json({ error: 'Failed to send WhatsApp message.' });
}
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
console.log(`ngrok forwarding URL (ensure it matches Vonage webhook config): Check your ngrok terminal.`);
if (!process.env.VONAGE_SMS_FROM_NUMBER) console.warn('WARN: VONAGE_SMS_FROM_NUMBER not set. Cannot send SMS.');
if (!process.env.VONAGE_WHATSAPP_SANDBOX_NUMBER) console.warn('WARN: VONAGE_WHATSAPP_SANDBOX_NUMBER not set. Cannot send WhatsApp via Sandbox.');
});
Explanation:
- Dependencies & Setup: We import necessary modules and initialize Express. dotenv.config() loads variables from .env.
- Vonage Client: We initialize the Vonage client using credentials from environment variables. Checks ensure essential credentials (including signature secret) exist, exiting if not. We comment out the apiHost override for the sandbox, preferring the default endpoint.
sendSmsFunction: Takes toNumber and messageText, constructs the payload for the Messages API (channel: 'sms'), and uses vonage.messages.send(). Basic logging for success and failure is included.sendWhatsAppFunction: Similar to sendSms, but uses the WhatsAppText class from @vonage/messages and specifies channel: 'whatsapp'. It uses the VONAGE_WHATSAPP_SANDBOX_NUMBER by default.rawBodyMiddleware&verifyWebhookSignature: This is crucial for security. Vonage signs webhook requests with a JWT using your Signature Secret. verifySignature needs the raw, unparsed request body. We create middleware (rawBodyMiddleware) using express.raw to capture this raw body before express.json() parses it for specific webhook routes. The verifyWebhookSignature function extracts the JWT from the Authorization header and uses @vonage/jwt's verifySignature method along with the raw body and your secret to validate the request. Crucially, if the signature secret is missing or verification fails, the function now returnsfalse, preventing insecure processing.- Webhook Endpoints (
/webhooks/inbound,/webhooks/status):
- These routes use the rawBodyMiddleware first, then express.json().
- They must call verifyWebhookSignature to ensure the request is legitimate. Unauthorized requests are rejected with 401.
- The /inbound handler logs the incoming message, extracts sender and content based on the channel, and optionally sends a reply using our helper functions.
- The /status handler logs delivery status updates.
- Both endpoints must respond with res.status(200).end() promptly to prevent Vonage from retrying the webhook.
- API Endpoints (
/api/send/sms,/api/send/whatsapp):
- Simple POST endpoints are added to trigger sending messages externally. These routes use the standard express.json() middleware applied after the webhook routes.
- They perform basic validation on the request body (to, message), including a simple digit check for the phone number, with notes on using better validation libraries. The error message clarifies the SDK's expectation for E.164 format.
- They call the respective sendSms or sendWhatsApp functions.
- Note: These endpoints lack proper authentication/authorization, which is essential for production (see Section 3). The @api comments are noted as usable with apidoc.
- Server Start: The server starts listening on the configured PORT. We add checks/warnings on startup for missing optional environment variables.
How Do You Secure and Enhance Your Messaging API for Production?
The example above includes basic API endpoints (/api/send/sms, /api/send/whatsapp). For a production system, you would enhance this layer significantly:
- Authentication & Authorization: Protect your API endpoints. Common methods include:
- API Keys: Issue unique keys to clients. Clients send the key in a header (e.g.,
X-API-Key). Your server validates the key against a stored list. - JWT (JSON Web Tokens): Implement a login flow where users/systems get a JWT upon successful authentication. They include the JWT in the
Authorization: Bearer <token>header for subsequent requests. Libraries likepassportwithpassport-jwtorpassport-http-bearer(for API keys) can help. - OAuth2: For third-party integrations or more complex authorization scenarios.
- Implementation Example (Conceptual - using a simple API key check middleware):
const VALID_API_KEYS = ['your-super-secret-key-1', 'another-key'];
function authenticateApiKey(req, res, next) {
const apiKey = req.headers['x-api-key'];
if (apiKey && VALID_API_KEYS.includes(apiKey)) {
console.log('API Key authenticated.');
next();
} else {
console.warn('API Key authentication failed.');
res.status(401).json({ error: 'Unauthorized: Invalid or missing API Key' });
}
}
app.post('/api/send/sms', authenticateApiKey, async (req, res) => { });
app.post('/api/send/whatsapp', authenticateApiKey, async (req, res) => { });
- Request Validation: Sanitize and validate all incoming data rigorously.
- Use libraries like
express-validatororjoito define schemas for request bodies and query parameters. - Check data types, lengths, formats (e.g., ensure phone numbers adhere to E.164 using libraries like
libphonenumber-js). - Example using
express-validator:
npm install express-validator libphonenumber-js
const { body, validationResult } = require('express-validator');
const { parsePhoneNumberFromString } = require('libphonenumber-js');
app.post('/api/send/sms',
authenticateApiKey,
body('to').custom(value => {
const numberToValidate = value.startsWith('+') ? value : `+${value}`;
const phoneNumber = parsePhoneNumberFromString(numberToValidate);
if (!phoneNumber || !phoneNumber.isValid()) {
throw new Error('Invalid E.164 phone number format required (e.g., +14155550100)');
}
return true;
}),
body('message').notEmpty().isLength({ min: 1, max: 1600 }).withMessage('Message is required and must be between 1 and 1600 characters'),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { to, message } = req.body;
}
);
Frequently Asked Questions
Can I send WhatsApp messages outside the 24-hour window?
WhatsApp enforces a 24-hour customer service window. When a user messages you or calls you, a 24-hour timer starts. During this window, you can send any type of message for free. After 24 hours, you can only send pre-approved message templates. The window resets each time the user responds. Plan your messaging strategy accordingly β use templates to initiate conversations, then engage freely within the 24-hour window.
How do I verify that webhooks are coming from Vonage?
Vonage signs webhook requests with a JWT (JSON Web Token) using HMAC-SHA256 and your signature secret. Always verify the signature before processing webhook data. The signature secret should be at least 32 bits and stored securely. Compare the JWT from the Authorization header against your secret using the @vonage/jwt library's verifySignature method. Additionally, compare a SHA-256 hash of the payload to the payload_hash claim in the JWT to guard against token replay attacks. Reject any requests that fail verification with a 401 status code.
What's the difference between the Vonage Sandbox and production WhatsApp?
The Vonage WhatsApp Sandbox uses a shared test number (14157386102) and allows you to test WhatsApp integration without a full WhatsApp Business Account setup. You must "allowlist" your number by sending a specific message to the Sandbox number. For production, you need a registered WhatsApp Business number linked to your Vonage application. The Sandbox is ideal for development and testing, but production requires proper WhatsApp Business API approval and your own dedicated business phone number.
How do I handle message delivery failures?
Monitor the status webhook (/webhooks/status) for delivery updates. Messages can fail for various reasons: invalid phone numbers, undelivered due to network issues, or rejected by WhatsApp. Implement retry logic with exponential backoff for transient failures. Log all message UUIDs and their status updates to track delivery rates. For critical messages, consider implementing a fallback channel (e.g., SMS) when WhatsApp delivery fails. Always handle errors gracefully in your sendSms and sendWhatsApp functions.
What phone number format does Vonage expect?
Vonage expects phone numbers in E.164 format without the leading + symbol. E.164 format includes the country code followed by the subscriber number (e.g., 14155550100 for a US number). Use libraries like libphonenumber-js to validate and format phone numbers correctly before sending them to the Vonage API. Invalid phone number formats will result in API errors and failed message delivery.
How do I secure my API endpoints for production use?
Never deploy the example endpoints to production without authentication. Implement API key validation, JWT-based authentication, or OAuth2 depending on your use case. Store API keys in a secure database or secrets management service, never in code. Use HTTPS for all communications. Implement rate limiting to prevent abuse. Validate all input data rigorously using libraries like express-validator. Consider implementing IP whitelisting for additional security. Load your Vonage private key from environment variables or a secure vault, never commit it to version control.
Can I send media files via WhatsApp using Vonage?
Yes, the Vonage Messages API supports sending images, videos, audio files, and documents via WhatsApp. Use the appropriate message type classes from @vonage/messages (e.g., WhatsAppImage, WhatsAppVideo, WhatsAppAudio, WhatsAppFile). Media files must be publicly accessible via HTTPS URL, or you can upload them using Vonage's media API. WhatsApp has file size limits: images (5 MB), videos (16 MB), audio (16 MB), and documents (100 MB). The file format must be supported by WhatsApp.
How do I test webhooks locally?
Use ngrok to expose your local Express server to the internet. Run ngrok http 3000 to create a public HTTPS URL that forwards to your local port 3000. Copy the ngrok HTTPS URL and configure it in your Vonage Application settings for both Inbound URL and Status URL (e.g., https://abc123.ngrok-free.app/webhooks/inbound). Ngrok provides a web interface at http://localhost:4040 where you can inspect all webhook requests and responses, making debugging easier.
What are the rate limits for the Vonage Messages API?
Vonage implements rate limiting to ensure fair usage and system stability. The specific limits depend on your account type and the messaging channel. WhatsApp has its own rate limits based on your business tier (Tier 1: 1,000 unique recipients per 24 hours, scaling up with verified quality). Implement proper error handling to catch rate limit errors (HTTP 429) and implement exponential backoff retry logic. Consider implementing a message queue for high-volume applications to smooth out traffic spikes and stay within rate limits.
How do I migrate from the Sandbox to production WhatsApp?
To move to production WhatsApp, register for a WhatsApp Business Account through Vonage. Complete the business verification process with Meta (Facebook). Once approved, you'll receive a dedicated WhatsApp Business number. Update your .env file to use your production WhatsApp number instead of the Sandbox number. Link your production number to your Vonage Application. Update webhook URLs if needed. Test thoroughly in production with real customer opt-ins. Ensure compliance with WhatsApp's Business Policy and Commerce Policy.
Related Resources:
- Vonage Messages API Documentation
- WhatsApp Business Platform Documentation
- Vonage Node.js SDK on npm
- Express.js Documentation
Use the Vonage Messages API and the Node.js Server SDK. After setting up a Vonage application and installing necessary dependencies, create an Express server with routes to handle sending messages and webhooks. The provided sendSms function handles sending messages through the API.
The Vonage Messages API is a unified interface for sending messages across various channels like SMS, MMS, WhatsApp, and more. It simplifies multi-channel communication by handling complexities of individual platforms through a single API.
The Vonage Node.js Server SDK streamlines authentication and message sending through the Vonage API. It handles low-level details, making integration easier by providing functions like messages.send().
Always verify webhook signatures for security, especially in production. This ensures incoming webhooks originate from Vonage and haven't been tampered with. The verifyWebhookSignature function and rawBodyMiddleware are crucial for this step.
Yes, use the Vonage Messages API Sandbox for initial testing. It lets you send and receive WhatsApp messages without a full business setup after linking a WhatsApp-enabled device.
Set up webhook endpoints in your Express server and configure the URLs in your Vonage Application settings. The /webhooks/inbound route receives message data and should respond with 200 OK quickly. You can send automated replies using this route after verifying the signature.
ngrok creates a public, secure tunnel to your local development server, enabling Vonage to send webhooks to your machine during development and testing.
Implement a webhook endpoint at /webhooks/status. This endpoint will receive POST requests from Vonage containing the message status (e.g., 'delivered', 'failed') and associated metadata.
Node.js version 18 or higher is recommended for this project, along with npm, which is included with the Node.js installation.
Implement authentication mechanisms like API keys, JWT, or OAuth2 to protect your endpoints. Validate all incoming data and use environment variables for sensitive information. Libraries like express-validator and passport are helpful.
The Vonage Application ID is a unique identifier for your application within Vonage, used for grouping your numbers, configuring webhooks, and managing credentials.
The private.key file is essential for authenticating your application with the Vonage API and should be kept secure. Never commit it to version control. Load securely in production, not directly from the file system.
Create a .env file in your project root and add your Vonage API key, secret, application ID, private key path, and other relevant configuration values. Use dotenv package to load these variables into your Node.js application.
In the Vonage Dashboard, go to your application settings. Under 'Linked Numbers', find your purchased virtual number and click the 'Link' button to associate it with your application.
Unify SMS, WhatsApp, and RCS Routing With SMSRoute
Managing separate SDKs, webhook formats, and carrier compliance rules across messaging channels slows engineering teams down. SMSRoute gives you one clean API with direct Tier-1 SMS fallback, live delivery webhooks, and instant no-KYC provisioning.
curl -X POST https://api.sendsmsnokyc.com/v3/messages \
-H "x-api-key: $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": ["+14155551234"],
"channel": ["sms", "whatsapp", "rcs"],
"body": "Your order #84213 has shipped."
}'
- Automatic Channel Fallback: Deliver rich messages where supported and fall back seamlessly to direct Tier-1 SMS when handsets are offline.
- Handset-Verified Carrier Testing: Audit real SIM delivery, latency, and Sender ID preservation via SMSRoute Live Carrier Testing.
- Transparent Global Pricing: Compare exact per-country rates on our live pricing page.
Build Resilient Multi-Channel Messaging on SMSRoute
Send SMS, WhatsApp, and RCS over direct carrier routes across 190+ countries with instant API access and crypto or card settlement.
Explore SMSRoute Developers β