Frequently Asked Questions
Use the Vonage Messages API and Fastify framework. Set up a Fastify server, integrate the Vonage Node.js SDK, and create a POST route to handle SMS sending requests. This setup allows your Node.js application to send SMS messages programmatically.
The Vonage Messages API is a service for sending messages through various channels like SMS. It's used to reliably deliver transactional and notification messages within applications. The API handles the complexities of message delivery, letting developers focus on application logic.
Fastify is a high-performance Node.js web framework known for speed and extensibility. Its efficient design minimizes overhead, making it ideal for handling API requests like those for sending SMS messages.
The Vonage Node.js SDK simplifies interactions with Vonage APIs. It handles authentication, request formatting, and response parsing. Use it whenever your Node.js application needs to communicate with Vonage services like the Messages API for SMS sending.
Obtain API Key and Secret from your Vonage dashboard, create a Vonage Application, generate and secure a private key, and link a Vonage virtual number or an Alphanumeric Sender ID. Update all these environment variables in your project's .env file.
Fastify-env loads and validates environment variables, ensuring your application has the necessary configuration values. It helps manage sensitive data like API keys and secrets securely. Use it in combination with the dotenv package for loading environment variables from a .env file during development.
Implement error handling within your Vonage service function to catch and log errors from the Vonage SDK. The route handler should also catch and re-throw errors with appropriate HTTP status codes (e.g., 400, 401, 500).
The application includes schema validation with @sinclair/typebox to sanitize input, basic IP rate limiting using fastify-rate-limit to prevent abuse, and environment variable management for secure credential storage. These mechanisms mitigate common security risks and improve application robustness.
Yes, if it's approved for your account. Instead of a phone number, you can configure an Alphanumeric Sender ID (e.g., 'MyApp') as the 'from' address for your SMS messages in your .env file under VONAGE_SMS_FROM
Organize your code into directories for plugins (env.js), routes (sms.js), and services (vonage.js). This modular structure promotes clean separation of concerns and maintainability. Create app.js for Fastify setup and server.js for launching the application.
Ensure you have Node.js (LTS recommended), npm, a Vonage API account, and a basic understanding of Node.js, asynchronous programming, and REST APIs. A tool for making HTTP requests (like cURL or Postman) is essential for testing.
A client sends a POST request to the Fastify API endpoint. The server validates the request and uses the Vonage Node.js SDK to call the Vonage Messages API. Vonage delivers the SMS, returns a response to the server, which then sends a final response to the client.
Populate the .env file with your credentials and test numbers, then run npm run dev. Send requests using tools like cURL or Postman to the /api/v1/send-sms endpoint with valid parameters. Use the provided cURL examples in the tutorial to test the API.
You can find your API Key, Secret, and Application settings in your Vonage API Dashboard. Navigate to the settings section to manage these settings. Ensure that 'Default SMS Setting' is set to 'Messages API'.
How to Send SMS Messages with Fastify and Vonage Messages API
Learn how to build a production-ready SMS API endpoint using Node.js, the Fastify web framework, and the Vonage Messages API. This comprehensive tutorial covers project setup, Vonage configuration, API implementation, security features, error handling, and testing—everything you need to send SMS messages programmatically from your Fastify application.
By the end of this guide, you'll have a functional Fastify API endpoint (
POST /api/v1/send-sms
) that accepts a phone number and message payload, then uses Vonage to deliver the SMS reliably. This solution is ideal for applications requiring transactional SMS, notification systems, or two-factor authentication messaging.Prerequisites
Before starting this SMS integration tutorial, ensure you have:
Technology Stack Overview
This tutorial uses the following technologies for building a robust SMS API:
@vonage/server-sdk
: Official Vonage Node.js SDK for seamless API interactiondotenv
: Environment variable management module required byfastify-env
fastify-env
: Fastify plugin for loading and validating environment variables securelyfastify-rate-limit
: Built-in rate limiting plugin for API protection@sinclair/typebox
: TypeScript-based schema validation library for Fastify routes and environment variablesSystem Architecture
Understanding the SMS API flow helps you implement and troubleshoot effectively:
/api/v1/send-sms
)Final Outcome: A production-ready Node.js Fastify API server with a single SMS endpoint (
POST /api/v1/send-sms
) that securely sends text messages using Vonage's reliable messaging infrastructure.1. Setting up the Node.js Project
Let's initialize the project structure and install all required dependencies for the SMS API.
Create Project Directory
Open your terminal and create a new directory for the Fastify SMS project:
Initialize Node.js Project
Create a
package.json
file to manage dependencies:Install Required Dependencies
Install Fastify, the Vonage SDK, and supporting packages for environment management, rate limiting, and validation:
Install
pino-pretty
as a development dependency for readable log output during development:Set up Project Structure
Create a well-organized project structure following Node.js best practices:
Directory explanation:
src/
: Contains core application logicplugins/
: Fastify plugins for environment variable handling and other cross-cutting concernsroutes/
: API endpoint definitionsservices/
: External service integrations like Vonageapp.js
: Configures and exports the Fastify instanceserver.js
: Application entry point that starts the server.env
/.env.example
: Environment variable management for API credentialsCreate
.gitignore
Prevent committing sensitive information and build artifacts by creating a
.gitignore
file:Create
.env.example
Create an
.env.example
file as a template for required environment variables:Create Local
.env
FileDuplicate
.env.example
to create your local configuration file:Security Note: Never commit your
.env
file to version control. Add your actual Vonage credentials in the next section.2. Integrating with Vonage Messages API
Before implementing the SMS functionality, configure your Vonage account and obtain the necessary API credentials.
Sign Up or Log In to Vonage
Ensure you have a Vonage API account. New accounts typically receive free credit for testing SMS functionality.
Set Messages API as Default
Configure Vonage to use the Messages API for SMS:
This ensures consistency across all Vonage features and enables access to advanced messaging capabilities.
Get API Key and Secret
Retrieve your basic API credentials:
.env
file forVONAGE_API_KEY
andVONAGE_API_SECRET
Note: While the Messages API primarily uses Application ID and Private Key for authentication, the SDK may require API Key/Secret for initialization.
Create a Vonage Application
The Messages API requires a Vonage Application to manage authentication and webhook settings:
https://example.com/inbound
,https://example.com/status
) since we're only sending SMS in this tutorialprivate.key
filefastify-vonage-sms/private.key
).env
file forVONAGE_APPLICATION_ID
VONAGE_PRIVATE_KEY_PATH
in.env
to the correct path (e.g.,./private.key
)Link a Vonage Number
You need a Vonage virtual number as the sender for outbound SMS:
14155550100
).env
file forVONAGE_SMS_FROM
Alternative: If approved for your account, use an Alphanumeric Sender ID (e.g., "MyApp").
Whitelist Test Numbers (Trial Accounts Only)
Trial Vonage accounts can only send SMS to verified numbers:
Your
.env
file should now contain all required Vonage credentials for SMS integration.3. Implementing Core SMS Functionality
Now we'll build the Fastify server, configure environment variables, create the Vonage service layer, and define the SMS API route.
Configure Environment Variables Plugin
Create
src/plugins/env.js
to load and validate environment variables:Key features:
@sinclair/typebox
to specify expected typesdotenv: true
enables automatic.env
file loadingconfKey: 'config'
makes variables accessible viafastify.config
Create Vonage Service Module
Create
src/services/vonage.js
to encapsulate Vonage SDK initialization and SMS sending logic:Implementation highlights:
initializeVonage
: Handles both file-based and inline private key content, with proper error handlingsendSms
: Callsvonage.messages.send
with required parameters for SMS channelpath.resolve
andprocess.cwd()
for reliable file path handlingCreate SMS API Route
Create
src/routes/sms.js
to define the SMS sending endpoint:Route features:
additionalProperties: false
prevents unexpected fieldsSet up Fastify Application
Create
src/app.js
to build the Fastify instance and register plugins:Application configuration:
pino-pretty
for development, JSON for production/api/v1
prefixCreate Server Entry Point
Create
server.js
to start the Fastify application:Startup features:
Add NPM Scripts
Update the
scripts
section in yourpackage.json
:npm start
: Production mode with JSON loggingnpm run dev
: Development mode with pretty-printed logs4. Testing Your SMS API
Now let's verify the SMS endpoint works correctly.
Verify Environment Configuration
Double-check that your
.env
file contains the correct Vonage credentials. If using a trial account, ensure the target phone number is added to your Test Numbers list in Vonage.Start the Development Server
Launch the server in development mode:
Expected output:
Send a Test SMS Request
Open a new terminal window and send a test request using cURL. Replace
+1YOUR_TEST_PHONE_NUMBER
with a verified test number in E.164 format:Verify the Response
Success response (HTTP 200):
The SMS should arrive on the target phone within seconds. Check your server terminal for confirmation logs.
Error response example (HTTP 400):
Check server logs for detailed error information if issues occur.
Test Input Validation
Verify that validation works correctly by testing invalid requests:
Missing required field:
Expected: 400 Bad Request with validation error about missing
to
property.Invalid phone format:
Expected: 400 Bad Request with pattern validation error.
Extra invalid property:
Expected: 400 Bad Request with additional properties error.
Test Health Endpoint
Verify the health check endpoint:
Expected response (HTTP 200):
5. Error Handling and Logging Best Practices
Proper error handling and logging are essential for maintaining a production SMS API.
Logging Implementation
The application uses Fastify's built-in Pino logger for structured logging:
npm run dev
): Usespino-pretty
for human-readable outputnpm start
): Outputs JSON format for log management systemsMonitor logs in the terminal where the server is running to track all SMS operations.
Error Handling Strategy
Validation Errors:
Vonage API Errors:
sendSms
service catches SDK errors and logs detailed informationInitialization Errors:
Retry Mechanisms
For simple API-triggered SMS sending, retries are typically handled by the calling client. For production systems with asynchronous workflows (job queues, background processing), consider:
async-retry
within thesendSms
function6. Security Features and Best Practices
Security is critical when building SMS APIs that handle user data and API credentials.
Input Validation
Implemented via Fastify's schema validation using
@sinclair/typebox
:additionalProperties: false
Rate Limiting
Basic IP-based rate limiting using
fastify-rate-limit
:max
andtimeWindow
based on expected usageSecret Management
API credentials are managed securely via environment variables:
.env
file (excluded from Git via.gitignore
)Private Key Handling
The service supports flexible private key management:
VONAGE_PRIVATE_KEY_PATH
Additional Security Recommendations
Security Headers:
Install and configure
@fastify/helmet
:Authentication:
Protect endpoints using API keys, JWT tokens, or OAuth with
@fastify/auth
:Dependency Security:
Regularly audit and update dependencies:
Frequently Asked Questions
How do I send SMS with Fastify and Vonage?
Install the
@vonage/server-sdk
package, configure your Vonage Application ID and private key, then create a Fastify route that callsvonage.messages.send()
with the recipient number, message content, and SMS channel configuration.What phone number format does Vonage require?
Vonage requires E.164 format for all phone numbers: a plus sign (+) followed by the country code and number without spaces or special characters. Examples:
+12125551234
(US),+442071838750
(UK).How much does it cost to send SMS with Vonage?
Vonage SMS pricing varies by destination country and message type. US SMS typically starts around $0.0076 per message segment. Check current pricing at vonage.com/communications-apis/sms/pricing.
Can I use Vonage with a trial account?
Yes, Vonage offers free trial credit for new accounts. Trial accounts can only send SMS to verified numbers added to your Test Numbers list in the Vonage Dashboard under Numbers → Test numbers.
How do I handle SMS delivery failures?
Implement error handling in your route handler to catch Vonage API errors. Log detailed error information for debugging. For production systems, consider implementing retry logic with exponential backoff for transient failures.
What is the SMS character limit for Vonage?
Standard SMS supports up to 160 characters (GSM-7 encoding) or 70 characters (Unicode). Longer messages are automatically segmented, with each segment billed separately. The maximum total length is 1,600 characters.
How do I secure my Vonage API credentials?
Store credentials in environment variables using
.env
files for development. In production, use secure secret management services like AWS Secrets Manager, Google Secret Manager, or HashiCorp Vault. Never commit credentials to version control.Can I send MMS with this setup?
Yes, the Vonage Messages API supports MMS. Modify the request to include image, audio, or video URLs in the message object. Check Vonage documentation for MMS-specific parameters and supported countries.
How do I monitor SMS delivery status?
Configure a Status URL webhook in your Vonage Application to receive delivery receipts. Vonage sends HTTP POST requests with delivery status updates (delivered, failed, etc.) to your webhook endpoint.
What Node.js version is required?
Use Node.js LTS version 18 or later for optimal compatibility with Fastify v5 and the latest
@vonage/server-sdk
features, including modern async/await patterns and security updates.Related Resources
Learn more about building SMS applications with Node.js and Fastify:
Next Steps: Now that you have a working SMS API, consider exploring advanced features like two-way messaging, delivery status webhooks, or bulk SMS campaigns. Check out our related tutorials for implementing these features with Fastify and Vonage.