Send SMS with Node.js, Express, and Vonage - code-examples -

Frequently Asked Questions

Use the Vonage API and the Node.js Server SDK. Set up an Express API endpoint that accepts the recipient's number and message, then uses the SDK to send the SMS via Vonage.
The Vonage API, a CPaaS platform, provides APIs for SMS, voice, video, and other communication services. In this Node.js application, we use it for sending text messages programmatically.
Dotenv loads environment variables from a `.env` file into `process.env`. It's essential for securely managing sensitive credentials like your Vonage API key and secret, keeping them out of your codebase.
Always validate phone numbers, especially in production. While the example provides a basic regex check, use a robust library like `libphonenumber-js` for accurate international validation and to prevent errors.
This tutorial focuses solely on sending SMS messages. Receiving messages requires setting up webhooks and is covered in separate Vonage documentation.
Install Express, the Vonage Server SDK, and dotenv. Create an endpoint (e.g., '/send') that accepts a POST request with 'phone' and 'message', then uses the SDK to send the SMS.
It's the phone number purchased or assigned within your Vonage account that SMS messages will be sent *from*. For trial accounts, use registered test numbers instead.
Separating the Vonage interaction (lib.js) from the server logic (index.js) improves code organization, testability, and makes swapping services or adding features easier.
Implement `try...catch` blocks to handle errors from the Vonage SDK. Log the errors and return appropriate error responses to the client. Consider retry mechanisms for transient errors in production.
If you need to store message history, user data, or schedule messages for later delivery, you'll need a database (e.g., PostgreSQL, MongoDB) and a data access layer.
Use input validation, rate limiting (`express-rate-limit`), authentication/authorization, and HTTPS. Manage API secrets securely via environment variables and never commit them to code.
E.164 is an international standard phone number format. It includes a '+' followed by the country code, area code, and subscriber number (e.g., +14155550100). Use this format for consistency and to avoid ambiguities.
This typically occurs with Vonage trial accounts. You're trying to send to a number not added to your verified Test Numbers list in the Vonage Dashboard.
Use platforms like Heroku, Vercel, or AWS. Configure environment variables directly in the platform, never commit your .env file. Use a process manager like PM2 for reliability.