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).envfile intoprocess.env, keeping credentials secureSystem Architecture:
An HTTP client (like
curlor a web application) sends a POST request to the/send-smsendpoint 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:
curlor Postman for testingExpected Outcome:
A running Node.js server with a
/send-smsendpoint. Sending a POST request with validtoandtextparameters 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.jsonto 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.jsto set up the Express server, initialize the Vonage SDK, and create the SMS sending function.Explanation:
dotenvfor credentials,expressfor the server, and theVonageclass from the SDKVonageinstance with API key and secret fromprocess.env. The SDK handles authentication using these credentials (SDK documentation)sendSmsFunction:asyncfunction encapsulating SMS logicfromnumber from environment variablesvonage.sms.send()withto,from, andtextparametersstatusproperty inresponseData.messages[0]['status']. Status'0'indicates success according to Vonage API documentationtry...catchfor network errors or SDK exceptionssuccess: true/falseand relevant data or error messagePORTfrom.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.jsbefore theapp.listencall (where the "// 5. Define the API endpoint" comment is).Explanation:
app.post('/send-sms', ...)listens for HTTP POST requests on/send-smsto(recipient) andtext(message) fromreq.body400 Bad Requestif missinggoogle-libphonenumbersendSms: 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)VonageSDK instance created with these credentials inindex.jsvonage.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
sendSmsfunction usestry...catchfor network or SDK-level errorsresponseData.messages[0].statusanderror-text) to detect API-specific errors (invalid number, insufficient balance)console.log,console.warn, andconsole.errorprovide 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
.envand.gitignore. In production, use environment variables from deployment platform or dedicated secrets managertoandtextpresence and format included. Use libraries likejoiorexpress-validatorfor complex validation in productionexpress-rate-limitto 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 Acceptedresponse. Separate worker process handles sendingvonageclient is initialized once and reused (already efficient)10. Monitoring and Analytics for SMS Delivery
/healthendpoint returning200 OKfor load balancers or monitoring systems/send-smsusing 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_KEYorVONAGE_API_SECRETin.env.envagainst Vonage Dashboard. Ensurerequire('dotenv').config();is called early. Check for extra spaces or charactersError:
Invalid 'From' numberVONAGE_VIRTUAL_NUMBERis incorrect, not owned by your account, or not SMS-capableError:
Non-Whitelisted Destination(Status code15)Error:
Missing Mandatory Field(Status code4or5)to,from, ortextparametersendSmsfunction and/send-smsendpoint 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.envfile in wrong locationrequire('dotenv').config();is first line inindex.js. Verify.envlocation (project root wherenoderuns)Caveat: Port Conflict (
EADDRINUSE)PORTin.env12. Production Deployment and CI/CD
Deployment Platforms: Deploy to Heroku, Render, AWS Elastic Beanstalk, Google Cloud Run, or VPS
Environment Variables: Never include
.envin deployment or Git commits. Configure variables (VONAGE_API_KEY,VONAGE_API_SECRET,VONAGE_VIRTUAL_NUMBER,PORT,NODE_ENV=production) in deployment platform's settingspackage.jsonScripts:Note:
devscript requires Node.js v18.11.0+. For broader compatibility, usenodemon index.js(requiresnpm install --save-dev nodemon). Most platforms automatically runnpm startCI/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
.envis correctly populated:You should see "Server listening..." in the console.
Manual Testing (using
curl): Open a new terminal. Replace+14155550100with valid test number (whitelisted for trial accounts):Check Expected Output:
curl:Automated Testing:
sendSmsin isolation. Mock@vonage/server-sdkto avoid actual API calls. Test different inputs and scenarios based on mocked responsessupertestto make HTTP requests to Express app. Test/send-smsendpoint, 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.