Developer Quick-Start: Step-by-step tutorial to send SMS messages using Node.js, Express, and Vonage SMS API. Complete guide with code examples, authentication setup, error handling, and production deployment tips. 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.
Learn how to send SMS messages programmatically using Node.js, Express, and the Vonage SMS API. This comprehensive tutorial covers everything from initial setup to production deployment, including authentication, error handling, and best practices for SMS integration.
By the end of this guide, you'll have a fully functional Express API endpoint that sends SMS messages to any phone number worldwide using the Vonage Node.js SDK. Perfect for building SMS notifications, alerts, two-factor authentication, or customer communication features in your Node.js applications.
Project Overview and Goals
- Goal: Create a REST API endpoint using Node.js and Express that sends SMS messages to specified recipients via the Vonage SMS API.
- Problem Solved: Send SMS messages programmatically from your applications, automating communication workflows.
- Technologies Used:
- Node.js: JavaScript runtime environment for server-side applications.
- Express: Minimal, flexible Node.js web framework for creating API endpoints.
- Vonage Node.js SDK: Library provided by Vonage to simplify SMS API interaction.
dotenv: Module to load environment variables from a .env file, keeping sensitive credentials secure.- Prerequisites:
- Node.js and npm (or yarn): Install from nodejs.org.
- Vonage API Account: Sign up for free at Vonage API Dashboard. New accounts receive free testing credit.
- A Text Editor or IDE: VS Code, Sublime Text, or WebStorm.
- API Testing Tool: curl, Postman, or Insomnia.
1. Setting up the Node.js Project
Create your project directory and set up dependencies and configuration for sending SMS with Node.js.
Project Structure
vonage-sms-guide/
βββ lib/
β βββ sms.js # SMS sending logic
βββ index.js # Express server & API endpoint
βββ .env # Environment variables (not in version control)
βββ .gitignore # Files to exclude from Git
βββ package.json # Project dependencies
Setup Steps
- Create Project Directory: Open your terminal and create a new directory for your project.
mkdir vonage-sms-guide
cd vonage-sms-guide
- 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 for the web server, the Vonage Server SDK for API
interaction, and
dotenvfor environment variables.
npm install express @vonage/server-sdk dotenv
- Enable ES Modules: Open your
package.jsonfile and add"type": "module"to use modernimport/exportsyntax.
{
"name": "vonage-sms-guide",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@vonage/server-sdk": "^3.13.0",
"dotenv": "^16.4.5",
"express": "^4.19.2"
},
"type": "module"
}
(Note: The versions shown are examples. Your package.json will reflect the specific versions
installed by npm install.)
- Create Environment File (
.env): Create a file named.envin the root of your project directory. This file stores your sensitive API credentials and configuration. Never commit this file to version control.
.env
# .env
# Server Configuration
PORT=3000
# Vonage API Credentials
VONAGE_API_KEY=YOUR_API_KEY
VONAGE_API_SECRET=YOUR_API_SECRET
# Vonage Sender Information
# Use either a purchased Vonage number (in E.164 format, e.g., +14155552671)
# or a registered Alphanumeric Sender ID (e.g., "MyApp")
VONAGE_VIRTUAL_NUMBER=YOUR_VONAGE_NUMBER_OR_SENDER_ID
Populate the VONAGE_ values in the next section.
- Create
.gitignoreFile: Prevent accidentally committing sensitive files and unnecessary directories by creating a.gitignorefile in the root of your project:
# .gitignore
# Dependencies
node_modules/
# Environment variables
.env
# Log files
*.log
# Operating system files
.DS_Store
Thumbs.db
- Create Project Directories: Create the
libdirectory for your SMS logic:
mkdir lib
2. Getting Your Vonage API Credentials
Retrieve your Vonage SMS API credentials and configure your account to send text messages.
- Retrieve API Credentials:
- Log in to your Vonage API Dashboard.
- Locate your API key and API secret on the main dashboard.
- Copy these values.
- Open your .env file and replace YOUR\_API\_KEY and YOUR\_API\_SECRET with your actual credentials.
.env
# .env (Example β use your actual credentials)
PORT=3000
VONAGE_API_KEY=a1b2c3d4
VONAGE_API_SECRET=e5f6g7h8i9j0k1l2
VONAGE_VIRTUAL_NUMBER=YOUR_VONAGE_NUMBER_OR_SENDER_ID
- Configure Sender Number/ID: Vonage requires a "from" number or identifier for your SMS messages. Choose one option:
- Vonage Virtual Number: Purchase a virtual phone number through the dashboard (Numbers β Buy numbers). These numbers support two-way messaging. Use E.164 format (e.g., +14155552671).
- Alphanumeric Sender ID: In supported countries, register a custom sender ID (like your brand name, e.g., "MyApp"). This supports one-way messaging only. Consult Vonage documentation for registration requirements.
Update VONAGE_VIRTUAL_NUMBER in your .env file with your chosen number or Sender
ID. .env
# .env (Example using a US number)
PORT=3000
VONAGE_API_KEY=a1b2c3d4
VONAGE_API_SECRET=e5f6g7h8i9j0k1l2
VONAGE_VIRTUAL_NUMBER=+14155552671
- Trial Account Limitation (Important):
- Free trial accounts can only send SMS messages to verified phone numbers within the dashboard.
- To add and verify test numbers:
- Navigate to your Vonage Dashboard.
- Find the "Getting started" section or "Test Numbers"/"Sandbox" area.
- Add the phone number(s) you want to test.
- Enter the verification code Vonage sends via SMS or voice call.
- Sending to unverified numbers on trial accounts returns a "Non-Whitelisted Destination" error. Add payment details to upgrade and send messages globally.
3. Implementing the SMS Sending Logic
Write the code that handles interaction with the Vonage SDK to send SMS messages programmatically.
SMS Sending Flow
1. Validate environment variables β 2. Initialize Vonage client β
3. Validate input parameters β 4. Send SMS via API β
5. Check response status β 6. Return success or throw error
Create the file lib/sms.js:
import { Vonage } from '@vonage/server-sdk';
import dotenv from 'dotenv';
dotenv.config();
if (!process.env.VONAGE_API_KEY || !process.env.VONAGE_API_SECRET || !process.env.VONAGE_VIRTUAL_NUMBER) {
console.error("Error: Missing Vonage API credentials or sender number in .env file.");
process.exit(1);
}
const vonage = new Vonage({
apiKey: process.env.VONAGE_API_KEY,
apiSecret: process.env.VONAGE_API_SECRET
});
const sender = process.env.VONAGE_VIRTUAL_NUMBER;
export const sendSms = async (recipient, message) => {
console.log(`Attempting to send SMS from ${sender} to ${recipient}`);
if (!recipient || !message) {
throw new Error("Recipient phone number and message text are required.");
}
if (!/^\+[1-9]\d{1,14}$/.test(recipient)) {
console.warn(`Recipient number ${recipient} might not be in valid E.164 format.`);
}
return new Promise((resolve, reject) => {
vonage.sms.send(sender, recipient, message, (err, responseData) => {
if (err) {
console.error("Vonage API Error:", err);
reject(new Error(`Failed to send SMS via Vonage: ${err.message || err}`));
} else {
if (responseData.messages[0]['status'] === "0") {
console.log("SMS submitted successfully:", responseData.messages[0]);
resolve(responseData);
} else {
const errorCode = responseData.messages[0]['status'];
const errorText = responseData.messages[0]['error-text'];
console.error(`Vonage Message Failed β Code: ${errorCode}, Error: ${errorText}`);
reject(new Error(`Vonage error ${errorCode}: ${errorText}`));
}
}
});
});
};
Code Breakdown:
- Imports: Import Vonage from the SDK and dotenv to load environment variables.
- Configuration Loading: dotenv.config() loads variables from .env. Basic checks ensure critical variables are present.
- Vonage Initialization: Create a Vonage instance using apiKey and apiSecret from environment variables. The comment clarifies this uses the legacy SMS API authentication and mentions the newer Messages API as the recommended alternative.
sendSmsFunction:
- Takes recipient and message as arguments.
- Includes basic logging and input validation (checking presence and a simple E.164 format regex).
- Wraps the vonage.sms.send(...) call in a Promise for easier async/await handling in the API layer.
- vonage.sms.send takes sender, recipient, message text, and a callback function.
- Callback Handling:
- Checks for network/request errors (err).
- If no request error, checks responseData.messages[0]['status']. Status "0" indicates success.
- If status is not "0", logs the error code and text from Vonage and rejects the promise with a descriptive error.
- On success, logs details and resolves the promise with responseData.
4. Building the Express API Endpoint
Create the Express server and REST API endpoint that uses the sendSms function to send text
messages.
Create the file index.js in the project root:
import express from 'express';
import dotenv from 'dotenv';
import { sendSms } from './lib/sms.js';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.status(200).json({
message: "Vonage SMS API Guide Server is running.",
sendEndpoint: "/send-sms (POST)",
requiredBody: { to: "+14155552671", text: "Your message content" }
});
});
app.post('/send-sms', async (req, res) => {
const { to, text } = req.body;
if (!to || !text) {
return res.status(400).json({
success: false,
message: "Missing required fields: 'to' (recipient phone number) and 'text' (message content) are required in the request body."
});
}
console.log(`Received request to send SMS to: ${to}`);
try {
const result = await sendSms(to, text);
console.log("Vonage API Response:", result);
res.status(200).json({
success: true,
message: "SMS submitted successfully to Vonage.",
data: result
});
} catch (error) {
console.error("Error in /send-sms endpoint:", error);
let statusCode = 500;
let errorMessage = "Failed to send SMS due to an internal server error.";
if (error.message.startsWith("Vonage error") || error.message.includes("Failed to send SMS via Vonage")) {
errorMessage = error.message;
if (error.message.includes("Non-Whitelisted Destination")) {
errorMessage = "Failed to send SMS: The recipient number is not whitelisted for this trial account. Verify the number in the Vonage dashboard.";
statusCode = 400;
} else if (error.message.includes("Invalid Credentials")) {
errorMessage = "Failed to send SMS: Invalid Vonage API Key or Secret. Check your .env file.";
statusCode = 500;
}
} else if (error.message.includes("Recipient phone number and message text are required")) {
statusCode = 400;
errorMessage = error.message;
}
res.status(statusCode).json({
success: false,
message: errorMessage
});
}
});
app.listen(PORT, () => {
console.log(`Server listening at http://localhost:${PORT}`);
console.log(`API Endpoint available at POST http://localhost:${PORT}/send-sms`);
});
Code Breakdown:
- Imports: Import express and our sendSms function.
- Initialization: Load dotenv, create the Express app, and define the PORT.
- Middleware: Use express.json() and express.urlencoded() to parse incoming JSON and form data in request bodies.
- Root Route (
/): A simple GET endpoint to confirm the server is running. /send-smsEndpoint (POST):
- Defined using app.post.
- Extracts to and text from req.body.
- Input Validation: Performs a basic check to ensure to and text are provided. Returns a 400 Bad Request if not.
- Call
sendSms: Calls the imported function within a try...catch block to handle potential errors (both network errors and Vonage API errors returned via promise rejection). - Success Response: If sendSms resolves successfully, sends a 200 OK response containing the success status and the data received from the Vonage API.
- Error Handling: If sendSms rejects, the catch block executes. It logs the error and sends an appropriate error response (usually 500 Internal Server Error, but checks for specific known error messages like validation failures or whitelisting issues to potentially return a 400 Bad Request).
- Server Start: app.listen starts the server on the specified port.
5. Testing Your SMS Endpoint
Run the Node.js application and test the SMS sending functionality.
- Verify
.envConfiguration: Verify your.envfile contains the correctVONAGE_API_KEY,VONAGE_API_SECRET, andVONAGE_VIRTUAL_NUMBER. Confirm the recipient phone number is whitelisted if using a trial account. - Start the Server: Open your terminal in the project root directory and run:
npm start
Or directly:
node index.js
Expected output:
Server listening at http://localhost:3000
API Endpoint available at POST http://localhost:3000/send-sms
- Test with
curl: Open a new terminal window. Replace[REPLACE_WITH_YOUR_VERIFIED_NUMBER]with your verified recipient phone number (in E.164 format, e.g.,+14155552671) and adjust the message text.
curl -X POST http://localhost:3000/send-sms \
-H "Content-Type: application/json" \
-d '{
"to": "[REPLACE_WITH_YOUR_VERIFIED_NUMBER]",
"text": "Hello from Node.js and Vonage!"
}'
- Expected Success Response: If the request succeeds, you should see output in the terminal
where
curlwas run similar to this (themessage-id,remaining-balance, andmessage-pricewill vary):
{
"success": true,
"message": "SMS submitted successfully to Vonage.",
"data": {
"message-count": "1",
"messages": [
{
"to": "1xxxxxxxxxx",
"message-id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6",
"status": "0",
"remaining-balance": "1.85000000",
"message-price": "0.00650000",
"network": "12345"
}
]
}
}
You should receive the SMS on the recipient phone shortly after. The terminal running the Node.js server will show log messages.
- Example Error Response (Missing Field): If you omit the
textfield:
curl -X POST http://localhost:3000/send-sms \
-H "Content-Type: application/json" \
-d '{"to": "[REPLACE_WITH_YOUR_VERIFIED_NUMBER]"}'
Response:
{
"success": false,
"message": "Missing required fields: 'to' (recipient phone number) and 'text' (message content) are required in the request body."
}
- Example Error Response (Non-Whitelisted Number on Trial):
{
"success": false,
"message": "Failed to send SMS: The recipient number is not whitelisted for this trial account. Verify the number in the Vonage dashboard."
}
6. Error Handling and Logging
Current Implementation
- The lib/sms.js function checks the status code from the Vonage response and rejects the promise with a specific error message if it's not "0".
- The index.js endpoint uses a try...catch block to handle promise rejections from sendSms.
- Basic input validation checks for required fields (to, text) in index.js.
- Specific error messages for common issues like missing fields, whitelisting problems, and invalid credentials are provided in the API response based on string matching of error messages.
- console.log and console.error are used for logging basic information and errors to the terminal.
Production Enhancements
Implement these patterns to improve reliability and observability:
- Structured Logging: Use a dedicated logging library like Pino or Winston for structured JSON logs, which are easier to parse and analyze. Include request IDs for tracing.
- Centralized Error Handling: Implement Express error-handling middleware for a more consistent way to catch and format errors across different routes.
- Detailed Vonage Errors: Consult the Vonage SMS API reference for a complete list of status codes (error-text) and handle critical ones more explicitly if needed (e.g., insufficient funds, barring).
- Custom Error Classes: Replace string matching (error.message.includes(...)) with custom error classes thrown from lib/sms.js or checking specific error codes provided by the Vonage SDK (if available) for more reliable error type detection in the catch block.
- Retry Mechanisms: For transient network errors or specific Vonage error codes indicating temporary issues, implement a retry strategy with exponential backoff using libraries like async-retry. Avoid retrying errors caused by invalid input.
7. Security Considerations
Security Checklist
| Security Layer | Implementation | Priority |
|---|---|---|
| API Credentials | Store in .env locally and use secure configuration management in production. Never
commit to version control. |
Critical |
| Input Validation | Use robust validation libraries like joi or express-validator to strictly validate
phone number format and message content. |
High |
| Rate Limiting | Implement express-rate-limit to prevent abuse and accidental loops.
|
High |
| Authentication/Authorization | Protect the endpoint with authentication (API keys, JWT tokens) to ensure only authorized clients can trigger SMS sends. | Critical |
| HTTPS | Run your Express application behind a reverse proxy (Nginx or Caddy) configured with TLS/SSL in production. | Critical |
| Input Sanitization | Sanitize input if it's ever reflected back or stored to prevent injection attacks. | Medium |
8. Troubleshooting and Caveats
Common Issues and Solutions
| Issue | Cause | Solution |
|---|---|---|
Non-Whitelisted Destination error |
Trial account sending to unverified number | Add and verify the recipient number in Vonage Dashboard under Test Numbers |
Invalid Credentials error |
Wrong API key/secret in .env |
Verify credentials match the dashboard exactly. Check .env file loading |
| Incorrect sender number | Invalid VONAGE_VIRTUAL_NUMBER |
Ensure the sender ID/number is valid, purchased/registered, and correctly formatted (E.164 for numbers) |
| Invalid recipient format | Phone number not in E.164 format | Use E.164 format: +14155552671 |
| Insufficient funds | Account balance depleted | Add credit in Vonage dashboard |
| API endpoint not found (404) | Wrong path, method, or port | Verify /send-sms path, POST method, and server port |
| JSON parsing errors | Missing or invalid Content-Type header | Include Content-Type: application/json header with valid JSON body |
| Vonage API downtime | Service outage | Check Vonage Status Page. Implement retries for resilience |
| Node.js version issues | Incompatible Node.js version | Use compatible LTS version of Node.js |
9. Deployment (Conceptual)
Deploy this application by running the Node.js process on a server and managing environment variables securely.
Deployment Checklist
| Step | Action | Tools/Platforms |
|---|---|---|
| 1. Choose Platform | Select hosting environment | Heroku, Vercel, Render, AWS EC2, Google Cloud, DigitalOcean, Docker/Kubernetes |
| 2. Configure Environment | Set environment variables securely (never upload .env) |
Heroku Config Vars, AWS Parameter Store/Secrets Manager, Docker environment flags |
| 3. Set Production Mode | Set NODE_ENV=production |
Environment variable configuration |
| 4. Build (if needed) | Run build step for TypeScript or bundling | TypeScript compiler, bundlers |
| 5. Process Management | Keep application running reliably | PM2 |
| 6. Reverse Proxy | Handle TLS/SSL termination and load balancing | Nginx, Caddy |
| 7. CI/CD | Automate testing and deployment | GitHub Actions, GitLab CI, Jenkins |
| 8. Monitoring | Track errors, performance, uptime | Application monitoring tools |
Conclusion
You've successfully built a Node.js and Express application that sends SMS messages programmatically using the Vonage SMS API with API Key/Secret authentication. This tutorial covered project setup, credential management, SMS sending logic with the Vonage Node.js SDK, API endpoint creation, testing, error handling, security, and deployment considerations.
Extend this foundation by:
- Implementing webhook endpoints to receive incoming SMS messages or delivery receipts.
- Adding more robust validation and error handling.
- Integrating a database to log sent messages.
- Building a user interface to trigger sends.
- Exploring other Vonage APIs (Voice, Verify, Video) or migrating to the Messages API for multi-channel support.
Frequently Asked Questions (FAQ)
How much does it cost to send SMS with Vonage?
Vonage pricing varies by destination country. New accounts receive free credit for testing. Check the Vonage Pricing page for specific rates. SMS typically costs $0.0075β$0.05 per message depending on the destination.
Can I send SMS to any phone number with a Vonage trial account?
No. Trial accounts can only send SMS to verified phone numbers added in the Vonage Dashboard. Verify test numbers before sending. Upgrade to a paid account by adding payment details to send messages globally without restrictions.
What is E.164 phone number format?
E.164 is the international phone number format required by Vonage. It includes a plus sign (+), country code,
and phone number without spaces or special characters. Example: +14155552671 for a US number.
How do I fix "Non-Whitelisted Destination" errors?
Add and verify the recipient number in your Vonage Dashboard under "Test Numbers" or upgrade your account to a paid plan.
What's the difference between Vonage SMS API and Messages API?
The SMS API uses API Key/Secret authentication and supports SMS only. The Messages API uses Application ID/Private Key authentication and supports multiple channels (SMS, WhatsApp, Viber, Facebook Messenger). Vonage recommends the Messages API for new applications.
Can I receive SMS messages with this setup?
This tutorial covers sending SMS only. To receive messages, configure webhook URLs in your Vonage Dashboard to receive inbound message notifications. Implement webhook endpoints in Express to handle incoming requests.
How do I handle SMS delivery receipts?
Configure delivery receipt webhooks in the Vonage Dashboard. Create an Express endpoint to receive delivery status updates (delivered, failed, expired). Use the message ID to track delivery status for each sent SMS.
Is the Vonage Node.js SDK production-ready?
Yes. The @vonage/server-sdk package is officially maintained by Vonage and suitable for
production. Implement proper error handling, rate limiting, and monitoring for production deployments.
Further Reading
- Vonage Node.js SDK Repository
- Vonage SMS API Documentation (Legacy API used in this guide)
- Vonage Messages API Documentation (Recommended for new applications, uses Application ID/Private Key)
- Express.js Documentation
- Node.js SMS Gateway Integration Guide
- SMS API Best Practices for Node.js Developers
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 β