Frequently Asked Questions
Use the Vonage SMS API with the Node.js SDK and Express. Create a POST endpoint that accepts the recipient's number and message, then use the SDK to send the SMS via Vonage's servers. The provided tutorial includes a step-by-step guide and code examples to get you started quickly.
The Vonage SMS API enables sending text messages programmatically from your applications. This guide specifically shows how to use the API with API Key and Secret authentication for sending outbound SMS messages from a Node.js backend.
Dotenv helps manage sensitive credentials like API keys and secrets by storing them in a '.env' file. This prevents accidentally committing these credentials to version control, enhancing security.
Use `vonage.sms.send()` when sending SMS messages with API Key and Secret authentication in the Vonage Node.js SDK. This method is suitable for straightforward SMS sending scenarios, as described in this guide.
The example provided in the tutorial sends to one recipient at a time. For sending to multiple recipients, you would need to loop through an array of numbers or adapt the API call within the SDK if it provides batch sending functionalities.
First, create a project directory and initialize a Node.js project with npm. Install `express`, `@vonage/server-sdk`, and `dotenv`. Create `index.js`, `.env`, and `.gitignore` files. Then, configure Vonage credentials and virtual number in the `.env` file.
Express.js provides the web server framework for creating the API endpoint that receives requests to send SMS messages. It handles routing the `/send-sms` request to the logic that interacts with the Vonage SMS API.
The provided code example demonstrates error handling by checking the 'status' field in the Vonage API response. A status of '0' signifies success, while other codes indicate errors, which are then handled appropriately.
During the trial period of a Vonage account, you must whitelist the recipient phone numbers for testing. Add the recipient's number to your approved test numbers in the Vonage dashboard to prevent the 'Non-Whitelisted Destination' error.
Log in to your Vonage API Dashboard, where the API Key and Secret are usually displayed on the main page or under 'API settings'. Copy these values for use in your application.
A Vonage virtual number serves as the sender ID for your SMS messages. You need a Vonage number to send SMS from, which you can obtain from the Vonage dashboard. Make sure it's in the correct format, such as +14155552671.
After starting your Node.js server, test the `/send-sms` endpoint with tools like `curl` or Postman. Send a POST request with the recipient's number and message in JSON format. Verify the response and check if the recipient received the SMS.
This error occurs when you're using a trial Vonage account and the recipient number isn't whitelisted. Ensure the recipient's number is added to your approved test numbers in the Vonage dashboard.
Double-check your Vonage API key and secret in your `.env` file for typos, making sure they match what's in your Vonage Dashboard. Ensure the `.env` file is loaded correctly using `require('dotenv').config()` early in your Node.js code.
This guide provides a step-by-step walkthrough for building a simple but functional Node.js application using the Express framework to send SMS messages via the Vonage SMS API. We will create a basic API endpoint that accepts a destination phone number and a message body, then utilizes the Vonage Node.js SDK to dispatch the SMS.
This tutorial focuses specifically on sending SMS messages using the Vonage SMS API with API Key and Secret authentication, which is a straightforward method for this task.
Project Overview and Goals
Goal: To create a simple REST API endpoint using Node.js and Express that allows sending SMS messages through the Vonage platform.
Problem Solved: Provides a basic programmatic way to send SMS notifications or messages from a backend application without complex setup.
Technologies Used:
@vonage/server-sdk
): Simplifies interaction with the Vonage APIs..env
file, keeping sensitive credentials out of the codebase.System Architecture:
Expected Outcome: A running Node.js Express server with a single POST endpoint (
/send-sms
). Sending a valid request to this endpoint will trigger an SMS message to the specified recipient via Vonage.Prerequisites:
+14155550100
) to send SMS from. You can get one in the dashboard (Numbers > Buy numbers). For trial accounts, you might need to use the number provided or purchase one if allowed.curl
for testing the API endpoint.1. Setting up the project
Let's start by creating our project directory and installing the necessary dependencies.
Create Project Directory: Open your terminal or command prompt and create a new directory for your project. Navigate into it.
Initialize Node.js Project: Initialize the project using npm. The
-y
flag accepts default settings.This creates a
package.json
file.Install Dependencies: Install Express for the web server, the Vonage SDK for interacting with the API, and
dotenv
for managing environment variables.Your
package.json
dependencies
section should now look similar to this (versions might vary):Create Core Files: Create the main application file and the environment configuration file.
index.js
: This will contain our Express server and API logic..env
: This file will store sensitive credentials like API keys (it should not be committed to version control)..gitignore
: To prevent committing sensitive files (.env
) and generated files (node_modules
).You can create these using your editor or via the terminal:
Configure
.gitignore
: Addnode_modules
and.env
to your.gitignore
file to ensure they aren't tracked by Git.Project Structure: Your basic project structure should now be:
2. Configuring Vonage Credentials
Before writing code, securely store your Vonage API credentials and virtual number.
Obtain Vonage Credentials:
FROM_NUMBER
). Copy this number (ensure it's in E.164 format, e.g.,+14155552671
). If you don't have one, you may need to buy one via ""Buy numbers"".Add Credentials to
.env
: Open the.env
file and add your credentials. Replace the placeholder values with your actual key, secret, and Vonage number.VONAGE_API_KEY
: Your API key from the Vonage dashboard.VONAGE_API_SECRET
: Your API secret from the Vonage dashboard.VONAGE_VIRTUAL_NUMBER
: The Vonage number you will send SMS from (e.g.,+14155552671
).PORT
: The port your Express server will listen on (defaulting to 3000 if not set).Whitelist Test Number (Trial Accounts): If you are using a trial account, ensure the phone number you intend to send SMS to is added to your list of approved test numbers in the Vonage dashboard. Failure to do this will result in a ""Non-Whitelisted Destination"" error. Look for sections like ""Test Numbers"" or similar under your account settings.
3. Implementing the SMS Sending Endpoint
Now, let's write the Node.js/Express code to create the server and the API endpoint.
Open
index.js
and add the following code:Code Explanation:
dotenv
to load variables,express
to create the server, and theVonage
class from the SDK.Vonage
SDK using theapiKey
andapiSecret
loaded from.env
. Basic checks ensure these environment variables are present.express.json()
andexpress.urlencoded()
are essential middleware functions that parse incoming request bodies, makingreq.body
available in our route handler./send-sms
Endpoint:POST
route at/send-sms
.to
(recipient number) andtext
(message content) are present in the request body.from
number (your Vonage virtual number) from environment variables.async/await
structure with atry...catch
block for cleaner asynchronous code handling and error management.vonage.sms.send({ to, from, text })
. Note: We use thesend
method of thevonage.sms
object here, passing the required parameters (to
,from
,text
). This method is suitable for API Key/Secret authentication. This method is asynchronous and returns a promise.status
field in the response from Vonage. A status of'0'
indicates successful submission.200 OK
) or failure (400 Bad Request
for Vonage errors,500 Internal Server Error
for SDK/network errors). Includes relevant details like message ID or error text.GET
route at/
to confirm the server is running.4. Basic Error Handling and Logging
The code above includes basic error handling:
to
andtext
parameters, returning a400 Bad Request
.500 Internal Server Error
or exiting.responseData.messages[0]['status']
and returns a400 Bad Request
with the Vonage error message.try...catch
block to handle exceptions during the API call (e.g., network timeouts, SDK issues) and returns a500 Internal Server Error
.console.log
andconsole.error
to output information about requests, successful submissions, and errors to the server console. For production, consider using a more robust logging library (like Winston or Pino).5. Testing the API Endpoint
Now, let's run the server and test the endpoint.
Run the Server: Open your terminal in the project directory (
vonage-sms-sender
) and run:You should see the output:
Server listening at http://localhost:3000
Test with
curl
: Open another terminal window and usecurl
to send a POST request. Replace+12345678900
with the whitelisted recipient phone number (in E.164 format) and customize the message text.Test with Postman (Alternative):
POST
.http://localhost:3000/send-sms
Expected Responses:
Success: You should receive the SMS on the recipient phone shortly. The API will respond with:
Your server console will show logs indicating the request and successful submission.
Validation Error (Missing Field):
Vonage Error (e.g., Non-Whitelisted Number):
Check your server console logs for more detailed error information.
Server Error (e.g., Bad Credentials):
6. Security Considerations (Basic)
.env
file or hardcode API keys/secrets directly in your source code. Use environment variables for all sensitive data. Ensure.env
is listed in your.gitignore
.to
number is a valid phone number format (e.g., using a library likelibphonenumber-js
).text
input to prevent potential injection attacks if the text is ever displayed elsewhere (though less critical for SMS sending itself).text
message.express-rate-limit
can easily add this functionality.7. Troubleshooting and Caveats
Non White-listed Destination
Error (Status Code 15): This is the most common issue for trial accounts. Ensure the recipient number (to
) is added to your Test Numbers list in the Vonage Dashboard.VONAGE_API_KEY
andVONAGE_API_SECRET
in your.env
file are correct and that the.env
file is being loaded (check for typos, ensurerequire('dotenv').config()
is called early). The specific error code returned by Vonage might differ based on the exact issue.VONAGE_VIRTUAL_NUMBER
is a valid number associated with your Vonage account and is in the correct E.164 format.from
andto
numbers should ideally be in E.164 format (e.g.,+14155552671
).@vonage/server-sdk
documentation if you encounter unexpected behavior after updates.vonage.sms.send
). Vonage also offers a more versatile Messages API (vonage.messages.send
) which handles multiple channels (SMS, MMS, WhatsApp, etc.) but uses Application ID and Private Key authentication, requiring different setup steps (creating a Vonage Application, generating keys). Choose the API that best suits your needs.8. Deployment (Conceptual)
Deploying this application involves hosting it on a server or platform-as-a-service (PaaS) and managing environment variables securely.
.env
file. All hosting platforms provide a secure way to configure environment variables for your deployed application (e.g., Heroku Config Vars, Vercel Environment Variables). ConfigureVONAGE_API_KEY
,VONAGE_API_SECRET
,VONAGE_VIRTUAL_NUMBER
, andPORT
in your chosen platform's settings.package.json
Scripts: Add astart
script to yourpackage.json
if you don't have one, which hosting platforms often use:Procfile
:Detailed deployment instructions vary significantly between platforms. Consult the documentation for your chosen hosting provider.
9. Verification and Testing
node index.js
. Does the server start without errors and log the listening message?http://localhost:3000/
in a browser or viacurl
?/send-sms
endpoint accept POST requests?200 OK
response withsuccess: true
and amessageId
?to
ortext
. Do you get a400 Bad Request
with the correct error message?400 Bad Request
indicating the whitelisting error (Non White-listed Destination
)?.env
and restart. Does the server fail to start or does the API call return an authentication error (e.g.,401 Unauthorized
or similar in the500
response)? Remember to restore correct credentials afterward.Conclusion
You have successfully built a basic Node.js Express application capable of sending SMS messages using the Vonage SMS API. This involved setting up the project, managing API credentials securely, implementing an API endpoint using the Vonage Node.js SDK, performing basic error handling, and testing the functionality.
Next Steps:
ngrok
for local development).vonage.messages.send()
.This foundation provides a starting point for integrating SMS capabilities into your Node.js applications.