Frequently Asked Questions
Use the Vonage Node.js SDK and Express to create an API endpoint. This endpoint receives recipient details and message content, then leverages the Vonage SMS API to send the message. The tutorial provides a detailed setup guide and code examples using the '@vonage/server-sdk' library.
The Vonage Node.js SDK ('@vonage/server-sdk') simplifies interaction with Vonage APIs within Node.js applications. It provides methods for various Vonage services, including sending SMS messages, making voice calls, and managing other communication channels.
Dotenv is used for managing environment variables. This keeps sensitive information like API keys and secrets out of your codebase. It loads these from a '.env' file, improving security and portability.
Using a Vonage virtual number as the sender is generally recommended for better reliability, two-way communication, and compliance with regulations in regions like North America. It's crucial for receiving replies and essential in certain countries.
Yes, in some countries. This uses a brand name (up to 11 characters) as the sender. However, country-specific regulations vary significantly. Many require pre-registration or disallow it entirely for application-to-person (A2P) messaging.
The tutorial demonstrates error handling using try-catch blocks and status code checking from the Vonage API response. User-friendly messages should be provided for common error scenarios, along with specific HTTP status codes for various failures.
The tutorial doesn't specify Vonage's default rate limits. You can implement your own rate limiting using middleware like 'express-rate-limit' to protect your API from abuse and manage costs, customizing limits as needed.
A basic regex is provided in the tutorial, but for production, use a library like 'libphonenumber-js'. This ensures proper E.164 formatting and handles international number variations reliably.
HTTPS encrypts communication between clients and your API. This protects sensitive data such as recipient phone numbers and message content. Always use HTTPS in production for security.
If you're on a Vonage trial account, go to your Dashboard settings, find "Test Numbers," and add the numbers you'll send test messages to. Verify ownership by entering the code Vonage sends to the added number.
The tutorial suggests an 'sms_logs' table with fields like 'id', 'recipient_number', 'sender_id', 'message_body', 'vonage_message_id', 'status_code', 'status_text', 'cost', 'sent_at', and 'updated_at' for comprehensive tracking.
Set up a webhook URL in your Vonage account settings, then create an endpoint in your Express app to receive POST requests from Vonage containing status updates (e.g., 'delivered', 'failed'). Process these updates in your app, such as by logging them in your database.
Configure an inbound message webhook in your Vonage settings to point to your app. Implement logic to identify keywords like STOP, UNSUBSCRIBE, and maintain a list of opted-out users to comply with regulations.
The tutorial emphasizes the asynchronous nature of Node.js for efficient request handling. Load testing, horizontal scaling, and queuing are recommended for higher throughput, especially with large volumes of messages.
Send SMS with Vonage API in Node.js: Complete Express Tutorial
Last Updated: January 2025
Framework Note: This tutorial demonstrates SMS implementation using Node.js with Express. The Vonage SMS API works with any Node.js framework. For framework-specific implementations like Next.js App Router, Server Actions, or database integration with Supabase, you can adapt the core SMS sending logic shown here to your preferred stack.
Build a production-ready Node.js application using Express to send SMS messages programmatically via the Vonage SMS API (formerly Nexmo). This comprehensive tutorial walks you through everything from initial project setup with the
@vonage/server-sdk
to implementing essential features like authentication, error handling, security best practices, and production deployment.By the end of this guide, you'll have a working Express REST API endpoint that sends SMS messages to any phone number worldwide. This foundation is perfect for building SMS-enabled features like two-factor authentication (2FA), transactional notifications, delivery alerts, appointment reminders, or verification codes.
Project Overview and Goals
Goal: Create a REST API endpoint using Node.js and Express that sends SMS messages via the Vonage SMS API.
Problem Solved: Enable programmatic SMS sending without managing complex telecom infrastructure or carrier integrations.
Technologies:
@vonage/server-sdk
): Official SDK that simplifies interaction with the Vonage SMS API and other Vonage services.dotenv
: Manages environment variables for configuration and secrets.Architecture: A client (like
curl
, Postman, or another application) sends an HTTP POST request to your Express API. The Express application validates the request, uses the Vonage SDK (configured with API credentials) to interact with the Vonage SMS API, which then delivers the message to the recipient's mobile device.(Note: For published documentation, consider replacing this ASCII diagram with a graphical version like SVG or PNG for better clarity.)
Prerequisites:
curl
or Postman).@vonage/server-sdk
: v3.25.x (latest version: 3.25.1, released September 2025)express
: v4.19.x, v4.20.x, or v5.1.0 (released March 31, 2025)dotenv
: v16.4.x1. Set Up Your Node.js Project
Initialize your Node.js project and install the Vonage SDK and required dependencies.
Create Your Project Directory: Open your terminal and create a new directory for the project, then navigate into it.
Initialize Your Node.js Project: Create a
package.json
file to manage your project dependencies and scripts.Install Your Dependencies: Install Express for the web server, the Vonage SDK to interact with the API, and
dotenv
to handle environment variables securely. Runningnpm install
without specific versions will install the latest stable releases.For production applications, pin to specific versions for reproducibility:
express
: The web framework.@vonage/server-sdk
: The official Vonage SDK for Node.js.dotenv
: Loads environment variables from a.env
file intoprocess.env
.Version Compatibility Note: The
@vonage/server-sdk
v3.x requires Node.js v14 or higher. For production use, prefer Node.js v20 or v22 LTS versions.Enable ES Modules (Optional but Recommended): Use ES Modules (
import
/export
) for modern JavaScript practice. Open yourpackage.json
file and add the following line:Create Your
.gitignore
File: Prevent sensitive files (like.env
andnode_modules
) from being committed to version control. Create a file named.gitignore
in the root directory:Create Your Project Files: Create the main application file and the environment configuration file.
Your project structure should now look like this:
2. Implement Core SMS Sending Functionality
Configure the Vonage SDK client and create the core function to send SMS messages programmatically.
Configure Your Environment Variables: Open the
.env
file. Replace the placeholder values (YOUR_API_KEY
,YOUR_API_SECRET
,YOUR_VONAGE_VIRTUAL_NUMBER
,MyApp
) with your actual credentials and chosen sender ID obtained from your Vonage Dashboard (see Section 4).VONAGE_API_KEY
/VONAGE_API_SECRET
: Found in your Vonage Dashboard (see Section 4). You must replace the placeholders.VONAGE_NUMBER
ORVONAGE_BRAND_NAME
: This is the 'from' identifier for your SMS.VONAGE_NUMBER
(in E.164 format, e.g.,14155550100
) is more reliable for SMS delivery, enables two-way messaging, and is required in some regions like the United States. ReplaceYOUR_VONAGE_VIRTUAL_NUMBER
if using this option.VONAGE_BRAND_NAME
(Alphanumeric Sender ID, up to 11 characters) is possible in some countries but often requires pre-registration and doesn't support replies. ReplaceMyApp
with your desired sender name if using this option. Be aware of limitations and country-specific rules (see Section 8).Initialize Vonage SDK and Create Send Function: Open
index.js
and add the following code:import 'dotenv/config'
automatically loads variables from.env
intoprocess.env
.Vonage
client using the API key and secret fromprocess.env
. Crucially, we add checks to ensure these variables are present.fromNumber
based on which environment variable (VONAGE_NUMBER
orVONAGE_BRAND_NAME
) is set, prioritizing the number if both are present.sendSms
function takes therecipient
number andmessage
text.vonage.sms.send()
, part of the SDK interacting with Vonage's standard SMS API.async/await
for cleaner handling of the promise returned by the SDK.status
in the response:'0'
means success. Any other status indicates an error reported by the Vonage API per the official Vonage troubleshooting documentation.{ success: boolean, data/message: ..., errorDetails: ... }
. We include specific user-friendly messages for common errors and link to the official documentation for all codes.try...catch
block handles potential network errors or SDK-level exceptions.3. Build Your Express API Layer
Create the Express server and configure the REST API endpoint for sending SMS messages.
Add the following code to the bottom of
index.js
:PORT
(defaulting to 3000 if not set in.env
).express.json()
andexpress.urlencoded()
middleware to parse incoming request bodies.POST /send-sms
route is defined:to
andtext
fields are present in the JSON request body.libphonenumber-js
for production use.sendSms
function with the validated data.success
property of the result fromsendSms
, setting appropriate HTTP status codes (200 for success, 400 for specific client errors like invalid number, 500 for other failures)./health
endpoint is added – useful for monitoring.app.listen
starts the server and logs helpful information, including a partial API key to confirm loading.4. Configure Vonage API Credentials
Obtain your Vonage API credentials and configure your SMS sender ID for message delivery.
Sign Up or Log In: Go to the Vonage API Dashboard and sign up or log in.
Find Your API Key and Secret: Once logged in, your API Key and API Secret are usually displayed prominently on the main dashboard page or within the "API settings" section. Look for values labeled
API key
andAPI secret
.Update Your
.env
File: Paste the copied key and secret into your.env
file, replacing theYOUR_API_KEY
andYOUR_API_SECRET
placeholders.Save the file after pasting your actual credentials.
Configure Your Sender ID (
VONAGE_BRAND_NAME
orVONAGE_NUMBER
): Decide how your messages will appear to recipients and configure the corresponding line in.env
:If using
VONAGE_BRAND_NAME
: Ensure the value in.env
is appropriate (e.g._MyApp
_ replacing the default placeholder). Be aware of country restrictions and potential registration needs (see Section 8).If using
VONAGE_NUMBER
:14155550100
).VONAGE_NUMBER
line in your.env
file and paste the purchased number there, replacingYOUR_VONAGE_VIRTUAL_NUMBER
. Comment out theVONAGE_BRAND_NAME
line.(CRITICAL for Trial Accounts) Add Test Numbers:
29
per Vonage SMS documentation).+
and country code).5. Handle Errors_ Logging_ and Retries
Enhance error handling and logging for production readiness.
Error Handling:
sendSms
function usestry...catch
to handle SDK/network errors.status
code from the Vonage API response for specific sending failures. According to Vonage's official SMS API error documentation_ status code0
indicates success_ while non-zero values indicate errors such as:1
- Throttled2
- Missing parameters3
- Invalid parameters4
- Invalid credentials9
- Partner quota violation (insufficient funds)15
- Invalid sender address (non-whitelisted destination in trial accounts)29
- Non-whitelisted destinationLogging:
console.log
andconsole.error
for basic operational logging.Retry Mechanisms:
6. Database Integration for SMS Logging (Optional)
Learn when and how to add database functionality for SMS audit logging and tracking.
sms_logs
with columns likeid
_recipient_number
_sender_id
_message_body
_vonage_message_id
_status_code
_status_text
_cost
_sent_at
_updated_at
).7. Add Security Features
Secure your API endpoint and credentials.
We implemented basic presence checks for
to
andtext
.Robust Phone Number Validation: Crucially_ replace the basic regex check with a dedicated library like
libphonenumber-js
. This library_ a JavaScript port of Google's libphonenumber_ can parse_ format_ and validate phone numbers for different regions_ ensuring they conform to the E.164 standard expected by Vonage.Message Content (
text
) Sanitization: While the risk of code injection directly via SMS is low compared to web contexts (SMS doesn't execute scripts)_ consider sanitization if:text
originates from untrusted user input.text
might be stored and later displayed in a web interface (prevent XSS).dompurify
if rendering in HTML) is usually unnecessary unless the message content has downstream uses beyond simple SMS delivery.Length Validation: Enforce a maximum length for the
text
field to prevent abuse and manage costs associated with multi-part messages. Standard SMS using GSM-7 encoding supports 160 characters; Unicode messages support 70 characters per segment.Secrets Management:
.env
File: Use.env
for local development only. Never commit the.env
file to version control (Git). Ensure.env
is listed in your.gitignore
file..env
file. Use the environment variable management system provided by your deployment platform (e.g._ Heroku Config Vars_ AWS Secrets Manager_ Google Secret Manager_ Azure Key Vault_ Docker environment variables). These services provide secure storage and injection of secrets into your application environment.Rate Limiting:
/send-sms
endpoint from abuse (e.g._ denial-of-service attacks_ spamming attempts) by limiting the number of requests a single client (IP address) can make within a certain time window.express-rate-limit
.HTTPS:
Authentication/Authorization (If Necessary):
X-API-Key
). Validate the key on the server.8. Handle Special Cases
Understand SMS delivery nuances and regional considerations.
+
followed by country code and the subscriber number (e.g._+447700900000
for UK_+12125550100
for US).libphonenumber-js
helps parse various input formats into E.164. Using this standard format ensures correct routing by Vonage and carriers.VONAGE_BRAND_NAME
vs.VONAGE_NUMBER
):VONAGE_BRAND_NAME
): Support varies greatly by country.VONAGE_NUMBER
): Using a Vonage-provided number (Long Code_ Toll-Free) is generally the most reliable and compatible method globally_ especially for two-way communication and delivery to regions like North America.VONAGE_BRAND_NAME
.POST /sms-status
) to receive HTTP POST requests from Vonage containing status updates (e.g._delivered
_failed
_expired
) for messages you sent.VONAGE_NUMBER
)_ you must:POST /inbound-sms
).9. Optimize Performance
Scale your SMS sending application effectively.
async/await
with the Vonage SDK's promise-based methods ensures your API call doesn't block the server while waiting for Vonage's response. This is crucial for handling concurrent requests efficiently./send-sms
endpoint will be the network latency and processing time of the Vonage API itself. This is external to your application.@vonage/server-sdk
handles underlying HTTP(S) connections. Modern SDKs typically use connection pooling to reuse connections_ reducing the overhead of establishing new connections for each request.k6
_artillery
_ApacheBench (ab)
) to simulate concurrent users hitting your/send-sms
endpoint./send-sms
endpoint quickly validates the request and adds the message details (recipient_ text) to a message queue (e.g._ RabbitMQ_ Redis Streams_ AWS SQS).sendSms
function to interact with the Vonage API.Related Resources
Frequently Asked Questions
Q: What's the difference between Vonage SMS API and Messages API? A: The SMS API is designed specifically for SMS/MMS messaging_ while the Messages API supports multiple channels (SMS_ WhatsApp_ Facebook Messenger_ Viber). This tutorial uses the SMS API via
vonage.sms.send()
. For multi-channel messaging_ explorevonage.messages.send()
.Q: How much does it cost to send SMS with Vonage? A: Vonage SMS pricing varies by destination country. Most messages cost between $0.01-$0.10 per SMS segment. Check the Vonage pricing page for specific rates. New accounts receive free credit for testing.
Q: Can I send SMS to international numbers? A: Yes_ Vonage supports SMS delivery to over 200 countries. Ensure phone numbers are in E.164 format with the correct country code. Pricing and delivery rates vary by country.
Q: Why am I getting "Non-Whitelisted Destination" errors? A: Trial accounts can only send SMS to verified test numbers. Add and verify recipient numbers in your Vonage Dashboard under Settings > Test Numbers before testing.
Q: How do I receive SMS replies with Node.js? A: Configure an inbound webhook URL in your Vonage Dashboard, then create a POST endpoint (e.g.,
/webhook/inbound
) in your Express app to receive incoming SMS data from Vonage.