Frequently Asked Questions
Use the Vonage Messages API with the Node.js SDK and Express. Set up a Vonage application and link a purchased Vonage number. Then, use `vonage.messages.send()` with the correct parameters, including your Vonage number, recipient number, and message content. Ensure your API keys and secrets are configured correctly in your .env file.
The Vonage Messages API is a unified platform for sending and receiving messages across various channels, including SMS, WhatsApp, Viber, and Facebook Messenger. It simplifies communication integration by providing a single interface for multiple messaging platforms. This allows developers to manage communication across different channels without separate integrations.
The Vonage Node.js SDK utilizes a private key to sign API requests, ensuring secure authentication. When you create a Vonage Application, you download a private key file (private.key). The SDK uses this key to sign each request. Vonage then verifies these signatures against the corresponding public key, confirming the request's authenticity and preventing unauthorized access.
ngrok is crucial during development to expose your local server's webhooks to the internet so Vonage can reach them. For production, deploy to a hosting provider and use its stable public URL for webhooks, as ngrok is not suitable for production environments.
Yes, during development, you can use the Vonage Messages API Sandbox to test sending and receiving WhatsApp messages without needing a full business account setup. Connect your personal WhatsApp number to the Sandbox to begin testing.
Use the `@vonage/jwt` package's `verifySignature` function. Pass it the JWT from the `Authorization` header, your `VONAGE_API_SIGNATURE_SECRET`, and the exact raw request body. This verification ensures that webhook requests truly originate from Vonage, enhancing security.
Vonage Applications act as containers that manage your communication settings and link your Vonage numbers to your code. They hold webhook URLs, manage linked numbers, and store authentication settings, enabling Vonage to route incoming messages and deliver status updates correctly.
In your Vonage Application settings, configure the Inbound URL to point to your server's endpoint (e.g., `https://your-app.com/webhooks/inbound`). In your Express app, define this route to handle incoming message data and always respond with a 200 OK status to prevent retries.
If your webhook endpoints don't return a 200 OK status promptly, Vonage assumes a failure and will retry the request multiple times. This can result in duplicate message processing or other unintended side effects.
Examine the `channel` and `message_type` fields in the webhook payload to determine the incoming message type (SMS, WhatsApp, etc.). Your logic can then process messages differently based on these values or other relevant fields like the content itself.
If webhooks aren't working, check if ngrok is running and correctly configured, if the right Vonage number is linked to the Vonage application, and that your Node.js server is running without errors. Also, review the ngrok interface for incoming requests and error logs for more details.
Protect API credentials (never commit `.env` or `private.key` to version control), always verify webhook signatures, validate API inputs thoroughly, and use rate limiting to prevent abuse.
Use the `WhatsAppText` class from the `@vonage/messages` package to structure the message payload. In your API request, provide the recipient's WhatsApp number, your Vonage WhatsApp Sandbox number (for testing), and the message text. Ensure your number is connected to the Vonage WhatsApp Sandbox.
This guide provides a complete walkthrough for building a Node.js application using the Express framework to send and receive both SMS and WhatsApp messages via the Vonage Messages API. We will cover setting up your environment, configuring Vonage, writing the core logic for sending and receiving messages, handling webhooks securely, and basic troubleshooting.
By the end of this tutorial, you will have a functional Express server capable of:
This enables developers to create applications that communicate with users on their preferred messaging channels through a unified API.
Project Overview and Goals
Goal: To create a simple yet robust Node.js Express application demonstrating how to leverage the Vonage Messages API for two-way SMS and WhatsApp communication.
Problem Solved: Managing communication across different channels (like SMS and WhatsApp) often requires separate integrations. The Vonage Messages API provides a single interface, simplifying development and allowing applications to reach users more effectively. This guide solves the initial setup and integration challenge for developers starting with Vonage messaging in a Node.js environment.
Technologies Used:
.env
file intoprocess.env
.System Architecture:
Prerequisites:
node -v
.npm -v
.1. Setting Up the Project
Let's initialize our Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal or command prompt and create a new directory for your project_ then navigate into it.
Initialize Node.js Project: Initialize the project using npm. The
-y
flag accepts the default settings.This creates a
package.json
file.Install Dependencies: Install Express_ the Vonage SDKs (
server-sdk
for core functionality_messages
for message types_jwt
for signature verification)_ anddotenv
.Create Core Files: Create the main application file and a file for environment variables.
Configure
.gitignore
: It's crucial not to commit sensitive information or unnecessary files. Add the following lines to your.gitignore
file:Set Up Environment Variables (
.env
): Open the.env
file and add the following variables. We will fill in the values in the next steps.VONAGE_API_KEY
_VONAGE_API_SECRET
: Your primary Vonage account credentials. Found on the Vonage API Dashboard homepage.VONAGE_APPLICATION_ID
: The unique ID for the Vonage Application you'll create to handle messaging.VONAGE_PRIVATE_KEY
: The file path to the private key downloaded when creating the Vonage Application. Crucial for authenticating SDK requests. Important: Like the.env
file_ ensure theprivate.key
file itself is listed in.gitignore
and never committed to version control.VONAGE_API_SIGNATURE_SECRET
: Used to verify the authenticity of incoming webhooks. Found in your Vonage Dashboard settings.VONAGE_NUMBER
: The virtual phone number you purchase/rent from Vonage_ capable of sending/receiving SMS.VONAGE_WHATSAPP_NUMBER
: The specific number provided by Vonage for sending WhatsApp messages_ especially the Sandbox number during development.PORT
: The local port your Express server will listen on.Project Structure:
Your project directory should now look like this:
(You will add
private.key
later)2. Configuring Vonage
Now_ let's configure the necessary components within your Vonage account.
Retrieve API Key and Secret:
.env
file forVONAGE_API_KEY
andVONAGE_API_SECRET
.Retrieve Signature Secret:
.env
file forVONAGE_API_SIGNATURE_SECRET
.Purchase a Vonage Number (for SMS):
12015550123
) and paste it into your.env
file forVONAGE_NUMBER
. Important: The SDK typically expects the number without a leading+
or00
(e.g.,12015550123
), but always consult the latest Vonage Node SDK documentation for the exact required format.Create a Vonage Application: Vonage Applications act as containers for your communication configurations (like webhooks) and link specific numbers to your code.
private.key
file. Save this file in the root of your project directory (vonage-messaging-app/
). Your.env
file already points to./private.key
. (Why? The SDK uses this private key to sign requests, authenticating them with the corresponding public key stored by Vonage.).env
file forVONAGE_APPLICATION_ID
.Link Your Vonage Number to the Application:
Set Up ngrok: ngrok creates a secure tunnel from the public internet to your local machine, allowing Vonage's servers to reach your development server.
Open a new terminal window (keep the first one for running the Node app later).
Navigate to your project directory (optional, but good practice).
Run ngrok, telling it to forward to the port defined in your
.env
file (default is 3000).ngrok will display output including a
Forwarding
URL ending in.ngrok.io
or.ngrok.app
(e.g.,https://<unique-id>.ngrok.io
). Copy this HTTPS URL.Configure Webhook URLs in Vonage Application:
/webhooks/inbound
. Example:https://<unique-id>.ngrok.io/webhooks/inbound
/webhooks/status
. Example:https://<unique-id>.ngrok.io/webhooks/status
Set Up Messages API Sandbox (for WhatsApp): The Sandbox provides a testing environment for WhatsApp without requiring a full WhatsApp Business Account setup initially.
14157386102
). Copy this number and paste it into your.env
file forVONAGE_WHATSAPP_NUMBER
./webhooks/inbound
(same as the application inbound URL)./webhooks/status
(same as the application status URL).Ensure Messages API is Default for SMS:
Use the Messages API
. Save changes if necessary. (Why? Vonage has older SMS APIs. This ensures your application uses the modern Messages API consistently.)Configuration is complete! You have your credentials, numbers, application, webhooks, and sandbox set up.
3. Implementing the Express Server and Core Logic
Now let's write the Node.js code in
index.js
.Code Explanation:
.env
variables, imports necessary modules (Express, Vonage SDK parts), initializes Express, and sets up middleware for parsing request bodies.Vonage
client instance using credentials and the private key path from environment variables. Includes a check for missing essential variables.verifyVonageSignature
):/webhooks/inbound
,/webhooks/status
).Authorization: Bearer <token>
header.verifySignature
from@vonage/jwt
, passing the token, yourVONAGE_API_SIGNATURE_SECRET
(from.env
), and the raw request body. Note: Usingexpress.json()
middleware parses the body before this point, which is compatible withverifySignature
as long asexpress.json()
is configured correctly and no other middleware modifies the body before verification. It's crucial that the body passed matches exactly what Vonage sent.next()
to pass control to the actual route handler.401 Unauthorized
response and stops processing. This is crucial for security./send-message
):POST
route.type
('sms' or 'whatsapp'),to
(recipient number), andtext
in the JSON request body.from
number based on thetype
.vonage.messages.send()
:message_type: ""text""
,channel: ""sms""
, etc.WhatsAppText
helper class for structuring the payload correctly.async/await
for cleaner handling of the promise returned by the SDK.202 Accepted
status on successful submission, along with themessage_uuid
./webhooks/inbound
):POST
route that uses theverifyVonageSignature
middleware first.200 OK
status back to Vonage immediately./webhooks/status
):POST
route, also protected byverifyVonageSignature
.delivered
,failed
,read
). You would add logic to update your application's state based on this.200 OK
back to Vonage.4. Running and Testing the Application
Ensure ngrok is Running: Verify that your
ngrok http 3000
command is still active in its terminal window and that the HTTPS URL matches the one configured in Vonage.Start the Node.js Server: In your primary terminal window (in the
vonage-messaging-app
directory), run:You should see the ""Server listening..."" message.
Test Sending SMS: Use a tool like
curl
or Postman to send a POST request to your/send-message
endpoint. Replace<YOUR_PHONE_NUMBER>
with your actual mobile number (including country code, no '+').Test Sending WhatsApp: Ensure your WhatsApp number is allowlisted in the Vonage Sandbox. Replace
<YOUR_WHATSAPP_NUMBER>
with your allowlisted number.Test Receiving SMS:
VONAGE_NUMBER
).Test Receiving WhatsApp:
VONAGE_WHATSAPP_NUMBER
).5. Security Considerations
.env
file orprivate.key
to version control. Use environment variable management systems provided by your deployment platform in production.verifyVonageSignature
middleware) is essential. It prevents attackers from sending fake requests to your webhook endpoints. Always use it for webhooks receiving data from Vonage./send-message
endpoint. In a production application, implement more robust validation (e.g., checking phone number formats, message length limits) for both API inputs and potentially webhook payloads before processing./send-message
) using libraries likeexpress-rate-limit
.6. Troubleshooting and Caveats
http://127.0.0.1:4040
) for incoming requests and potential errors.VONAGE_API_SIGNATURE_SECRET
in.env
is correct and matches the one in Vonage Dashboard settings.verifySignature
function receives the request body exactly as Vonage sent it. Middleware order can sometimes affect this, butexpress.json()
before the verifier is generally fine. Ensure no other middleware is unexpectedly modifying the raw body before verification.Authorization: Bearer <token>
).VONAGE_API_KEY
,VONAGE_API_SECRET
,VONAGE_APPLICATION_ID
are correct.private.key
exists at the specified path and is readable by the Node process.from
number.401 Unauthorized
Errors (Sending): Usually indicates problems with API Key/Secret or Application ID/Private Key authentication. Double-check these values and theprivate.key
file path and content.200 OK
on Webhooks: If your webhook endpoints don't consistently return a200 OK
status quickly, Vonage will retry, leading to duplicate logs/processing. Ensure your webhook logic is fast or defers long-running tasks.7. Deployment Considerations (Beyond this Guide)
.env
in your deployment package).pm2
to keep your Node.js application running reliably in production.Conclusion
You have successfully built a Node.js Express application capable of sending and receiving both SMS and WhatsApp messages using the Vonage Messages API. You learned how to configure Vonage, handle webhooks securely with signature verification, and implemented the core logic for sending messages via different channels.
This foundation enables you to build more complex communication features, such as automated replies, interactive bots, notification systems, and two-factor authentication flows, reaching users on the channels they prefer.
Next Steps: