Frequently Asked Questions
Use the Vonage SMS API with the Node.js SDK and Express. Create an API endpoint that accepts recipient number and message text, then uses the SDK to send the SMS via Vonage.
The Vonage Node.js SDK (@vonage/server-sdk
) simplifies interaction with the Vonage APIs. It handles authentication and request formatting, making it easier to send SMS messages from your Node.js application.
For trial accounts, Vonage requires whitelisting recipient numbers in the dashboard for security and to prevent abuse. This restriction is lifted once the account is upgraded with billing details.
While this guide uses the simpler vonage.sms.send()
method, Vonage's Messages API offers more advanced features. Consider it for richer messaging needs beyond basic SMS.
Yes, use the E.164 format (+[country code][number]). Ensure your Vonage account and number are enabled for the destination countries and that you comply with any applicable regulations.
Initialize a Node project with npm init
, install express
, @vonage/server-sdk
, and dotenv
. Create index.js
, .env
, and .gitignore
. Add API keys and virtual number to .env
and implement the SMS sending logic.
The .env
file stores sensitive information like your Vonage API key, secret, and virtual number. It's crucial for security and should never be committed to version control.
Use try...catch
blocks for network/SDK errors. Check the Vonage API response status for success ('0') or specific error codes. Implement robust logging for easier debugging and monitoring in production.
Start your server locally with node index.js
. Use a tool like curl
or Postman to send POST requests to your /send-sms
endpoint with test data, ensuring whitelisted recipient numbers in trial accounts. Check responses and logs to verify successful SMS delivery.
In production, use retry mechanisms with exponential backoff for handling transient errors like network issues or rate limiting. Avoid retrying permanent errors like invalid API keys.
Use a secrets manager for API keys, implement robust input validation, rate limiting, and appropriate authentication/authorization for the /send-sms
endpoint.
Standard SMS messages are limited to 160 characters (GSM-7 encoding). Longer messages may be split, incurring costs for multiple segments. Special characters might force UCS-2, further reducing per-segment limits.
Configure a webhook URL in your Vonage Dashboard settings to receive delivery reports. This will notify your application when a message is delivered, failed, or rejected.
Double-check your VONAGE_API_KEY
and VONAGE_API_SECRET
in the .env
file and your Vonage Dashboard. Ensure the .env
file is loaded correctly early in your application.
Several reasons include carrier issues, incorrect recipient number, temporary network problems, or country-specific restrictions. Verify the recipient number, consult Vonage Dashboard logs, and consider setting up delivery receipts.
How to Send SMS with Node.js and Vonage API: Complete Tutorial
This guide provides a complete walkthrough for building a Node.js and Express application that sends SMS messages using the Vonage SMS API. You'll learn everything from project setup to deployment and troubleshooting.
By the end, you'll have a functional REST API endpoint that accepts a phone number and message text, then uses the Vonage API to programmatically send SMS messages. This serves as a foundation for applications requiring SMS notifications, two-factor authentication, user verification, or other communication features.
Project Overview and Goals
What You're Building:
A minimal REST API built with Node.js and Express. This API exposes a single endpoint (
POST /send-sms
) that takes a recipient phone number and message body, and uses the Vonage Node.js SDK to send the SMS via the Vonage SMS API. This guide focuses on core functionality; production deployments require additional security, error handling, and scalability enhancements (discussed later).Problem Solved:
Provides a straightforward, server-side mechanism to programmatically send SMS messages, abstracting direct Vonage API interaction into a simple API call.
Technologies Used:
@vonage/server-sdk
): Simplifies Vonage API interaction, handling authentication and request formatting (GitHub repo).env
file intoprocess.env
, keeping credentials secureSystem Architecture:
An HTTP client (like
curl
or a web application) sends a POST request to the/send-sms
endpoint of your Node.js/Express server. The server uses the Vonage SDK, configured with API credentials, to request the Vonage SMS API. Vonage then sends the SMS to the recipient's phone.Prerequisites:
curl
or Postman for testingExpected Outcome:
A running Node.js server with a
/send-sms
endpoint. Sending a POST request with validto
andtext
parameters results in an SMS sent via Vonage.1. Setting Up Your Node.js SMS Project
Initialize your Node.js project and install dependencies.
Create Project Directory:
Initialize npm:
This creates
package.json
to manage dependencies and scripts.Install Dependencies:
Create Project Files:
Configure
.gitignore
: Add these lines to prevent committing dependencies and sensitive credentials:Configure Environment Variables (
.env
): Replace placeholder values with your actual credentials from the Vonage Dashboard:VONAGE_API_KEY
/VONAGE_API_SECRET
: SDK uses these to authenticate requestsVONAGE_VIRTUAL_NUMBER
: The "From" number appearing on recipient's phone (must be associated with your account)PORT
: Local port for your Express serverProject Structure:
2. Implementing Core SMS Functionality
Write the code in
index.js
to set up the Express server, initialize the Vonage SDK, and create the SMS sending function.Explanation:
dotenv
for credentials,express
for the server, and theVonage
class from the SDKVonage
instance with API key and secret fromprocess.env
. The SDK handles authentication using these credentials (SDK documentation)sendSms
Function:async
function encapsulating SMS logicfrom
number from environment variablesvonage.sms.send()
withto
,from
, andtext
parametersstatus
property inresponseData.messages[0]['status']
. Status'0'
indicates success according to Vonage API documentationtry...catch
for network errors or SDK exceptionssuccess: true/false
and relevant data or error messagePORT
from.env
(defaults to 3000), starts Express server, logs confirmation and warnings if credentials are missing3. Building the REST API Endpoint
Add the API endpoint to
index.js
before theapp.listen
call (where the "// 5. Define the API endpoint" comment is).Explanation:
app.post('/send-sms', ...)
listens for HTTP POST requests on/send-sms
to
(recipient) andtext
(message) fromreq.body
400 Bad Request
if missinggoogle-libphonenumber
sendSms
: Invokes the function with validated parameters200 OK
): Returns success message and Vonage response data500 Internal Server Error
): Returns error message. More refined implementations might map specific Vonage errors to different HTTP status codes4. Vonage API Integration Setup
Integration occurs during setup and initialization:
.env
(VONAGE_API_KEY
,VONAGE_API_SECRET
,VONAGE_VIRTUAL_NUMBER
)Vonage
SDK instance created with these credentials inindex.js
vonage.sms.send()
handles communication with Vonage API, including authentication headersvonage.sms.send
). For receiving messages, this setting changes webhook formats5. Error Handling, Logging, and Retry Logic
sendSms
function usestry...catch
for network or SDK-level errorsresponseData.messages[0].status
anderror-text
) to detect API-specific errors (invalid number, insufficient balance)console.log
,console.warn
, andconsole.error
provide visibility1
), implement retry strategy with exponential backoff using libraries likeasync-retry
. Wrapvonage.sms.send()
in a retry loop with progressive waits. Don't retry permanent errors (invalid API key, invalid recipient)6. Database Schema
Not applicable for this simple SMS API. For tracking sent messages, storing templates, or managing users, add a database (PostgreSQL, MongoDB) and data layer (ORM like Prisma or Sequelize).
7. Security Best Practices for SMS APIs
.env
and.gitignore
. In production, use environment variables from deployment platform or dedicated secrets managerto
andtext
presence and format included. Use libraries likejoi
orexpress-validator
for complex validation in productionexpress-rate-limit
to prevent API abuse (limit requests per IP)8. Handling International SMS and Special Cases
+
followed by country code and number) is standard. Vonage routes based on this. Ensure your account/number is enabled for destination countriesdelivered
,failed
,rejected
). Requires adding another endpoint to your Express app for callbacks9. Performance Optimization for High-Volume SMS
Not critical for single SMS messages. For high volumes, consider:
202 Accepted
response. Separate worker process handles sendingvonage
client is initialized once and reused (already efficient)10. Monitoring and Analytics for SMS Delivery
/health
endpoint returning200 OK
for load balancers or monitoring systems/send-sms
using monitoring tools (Prometheus/Grafana, Datadog). Track Vonage API call latency and success/error rates11. Common Issues and Troubleshooting
Error: 401 Unauthorized (
Authentication failed
)VONAGE_API_KEY
orVONAGE_API_SECRET
in.env
.env
against Vonage Dashboard. Ensurerequire('dotenv').config();
is called early. Check for extra spaces or charactersError:
Invalid 'From' number
VONAGE_VIRTUAL_NUMBER
is incorrect, not owned by your account, or not SMS-capableError:
Non-Whitelisted Destination
(Status code15
)Error:
Missing Mandatory Field
(Status code4
or5
)to
,from
, ortext
parametersendSms
function and/send-sms
endpoint logic. Review logs for validation errorsSMS Not Received, but API shows Success (
status: '0'
)Caveat: Environment Variables Not Loading
require('dotenv').config();
not called, called too late, or.env
file in wrong locationrequire('dotenv').config();
is first line inindex.js
. Verify.env
location (project root wherenode
runs)Caveat: Port Conflict (
EADDRINUSE
)PORT
in.env
12. Production Deployment and CI/CD
Deployment Platforms: Deploy to Heroku, Render, AWS Elastic Beanstalk, Google Cloud Run, or VPS
Environment Variables: Never include
.env
in deployment or Git commits. Configure variables (VONAGE_API_KEY
,VONAGE_API_SECRET
,VONAGE_VIRTUAL_NUMBER
,PORT
,NODE_ENV=production
) in deployment platform's settingspackage.json
Scripts:Note:
dev
script requires Node.js v18.11.0+. For broader compatibility, usenodemon index.js
(requiresnpm install --save-dev nodemon
). Most platforms automatically runnpm start
CI/CD Pipeline (GitHub Actions example):
.github/workflows/deploy.yml
) that:npm ci
– preferred in CI for usingpackage-lock.json
)npm test
)actions/heroku-deploy
,google-github-actions/deploy-cloudrun
)Rollback: Most platforms offer mechanisms to redeploy previous versions (e.g., Heroku's
heroku rollback
, AWS CodeDeploy strategies)13. Testing Your SMS API
Start the Server Locally: Ensure
.env
is correctly populated:You should see "Server listening..." in the console.
Manual Testing (using
curl
): Open a new terminal. Replace+14155550100
with valid test number (whitelisted for trial accounts):Check Expected Output:
curl
:Automated Testing:
sendSms
in isolation. Mock@vonage/server-sdk
to avoid actual API calls. Test different inputs and scenarios based on mocked responsessupertest
to make HTTP requests to Express app. Test/send-sms
endpoint, validating inputs, responses, and status codesFrequently Asked Questions
How do I send SMS messages from Node.js?
To send SMS from Node.js, install the Vonage SDK (
npm install @vonage/server-sdk
), initialize it with your API credentials, and callvonage.sms.send()
with the recipient number, sender number, and message text. This guide provides a complete implementation with Express.What is the best SMS API for Node.js?
Vonage SMS API (formerly Nexmo) is one of the most popular choices for Node.js due to its comprehensive SDK, reliable delivery, and competitive pricing. Other options include Twilio, AWS SNS, and MessageBird. The choice depends on your requirements for features, pricing, and geographic coverage.
How much does it cost to send SMS with Vonage?
Vonage SMS pricing varies by destination country. Most messages cost between $0.0045-0.02 USD per SMS segment. New accounts receive free credit for testing. Check the Vonage Pricing page for specific rates.
What is E.164 phone number format?
E.164 is the international phone number format required by most SMS APIs. It consists of a plus sign (+) followed by the country code and phone number, with no spaces or special characters (e.g., +14155552671 for a US number).
How many characters can I send in an SMS?
Standard SMS supports 160 GSM-7 characters or 70 Unicode characters per message. Longer messages are automatically split into concatenated SMS segments, with each part counting as a separate billable message. Characters from the GSM extended table use 2 bytes each.
Can I send SMS to international numbers?
Yes, Vonage supports SMS delivery to over 200 countries. Ensure your phone numbers use E.164 format with the correct country code. Note that trial accounts may have restrictions on international destinations until you add billing details.
How do I handle SMS delivery failures?
Implement comprehensive error handling by checking the status code in Vonage's response. Status '0' indicates success, while other codes indicate specific errors (invalid number, insufficient balance, etc.). Set up delivery receipt webhooks for real-time delivery confirmation.
What's the difference between Vonage SMS API and Messages API?
The SMS API (used in this guide) is optimized for simple text messaging and is in General Availability. The Messages API is a newer, more feature-rich platform supporting SMS, MMS, WhatsApp, Facebook Messenger, and Viber through a unified interface.
Next Steps
After completing this tutorial, consider these enhancements:
References
This guide provides a solid foundation for sending SMS messages with Node.js, Express, and Vonage. Adapt error handling, security, logging, and deployment strategies to fit your production requirements.