This guide provides a step-by-step walkthrough for building a simple yet robust Node.js application using the Express framework to send SMS messages via the Vonage Messages API. We'll cover everything from project setup and configuration to core implementation, error handling, and deployment considerations.
By the end of this guide, you will have a functional API endpoint capable of accepting a phone number and message text, and then using Vonage to dispatch the SMS. This serves as a foundational building block for applications requiring SMS notifications, alerts, or communication features.
Key Technologies:
- Node.js: A JavaScript runtime environment for building server-side applications.
- Express: A minimal and flexible Node.js web application framework.
- Vonage Messages API: A unified API for sending messages across various channels, including SMS. We'll use the
@vonage/server-sdk
Node.js library and potentially related packages like@vonage/messages
. - dotenv: A module to load environment variables from a
.env
file intoprocess.env
.
System Architecture:
A client (like a frontend application, another backend service, or a testing tool like curl
/Postman) sends an HTTP POST request to our Node.js/Express API. The API validates the request, uses the Vonage SDK (authenticated with your credentials) to interact with the Vonage Messages API, which then handles the delivery of the SMS message to the recipient's phone.
[Client] --(HTTP POST /send-sms)--> [Node.js/Express API] --(Vonage SDK)--> [Vonage Messages API] --(SMS Network)--> [Recipient Phone]
Prerequisites:
- Node.js and npm (or yarn): Installed on your development machine. Download Node.js
- Vonage API Account: Sign up for free at Vonage. You'll receive some free credits for testing.
- Vonage Phone Number: Purchase or use a Vonage virtual number capable of sending SMS. You can manage numbers in your Vonage Dashboard.
- Vonage Application: Create a Vonage application to obtain an Application ID and generate a private key file.
- (Optional but Recommended) Testing Tool:
curl
(command-line) or Postman (GUI) for testing the API endpoint.
1. Setting up the Project
Let's initialize our Node.js project and install the necessary dependencies.
-
Create Project Directory: Open your terminal and create a new directory for the project, then navigate into it.
mkdir vonage-sms-sender cd vonage-sms-sender
-
Initialize npm: Initialize the project using npm. The
-y
flag accepts the default settings.npm init -y
This creates a
package.json
file. -
Install Dependencies: Install Express (web framework), the Vonage Server SDK, the Vonage Messages package, and dotenv (for environment variables).
npm install express @vonage/server-sdk @vonage/messages dotenv --save
express
: Handles HTTP requests and routing.@vonage/server-sdk
: The official Vonage library for core configuration.@vonage/messages
: The Vonage library specifically for the Messages API.dotenv
: Loads environment variables from a.env
file, keeping sensitive credentials out of your code.
-
Create Project Files: Create the main application file and the environment configuration file.
touch index.js .env .gitignore
index.js
: This will contain our Express application code..env
: This file will store our sensitive API credentials and configuration. Never commit this file to version control..gitignore
: Specifies intentionally untracked files that Git should ignore.
-
Configure
.gitignore
: Addnode_modules
and.env
to your.gitignore
file to prevent committing dependencies and sensitive credentials.# Dependencies node_modules/ # Environment variables .env # Vonage private key file (if stored locally) private.key
-
Set up
.env
File: Open the.env
file and add the following placeholders. We will obtain these values in the "Integrating with Vonage" section.# Server Configuration PORT=3000 # Vonage Credentials & Configuration VONAGE_APPLICATION_ID=YOUR_VONAGE_APPLICATION_ID VONAGE_PRIVATE_KEY_PATH=./private.key # Or the actual path to your key file VONAGE_FROM_NUMBER=YOUR_VONAGE_VIRTUAL_NUMBER
PORT
: The port number your Express server will listen on.VONAGE_APPLICATION_ID
: Your unique Vonage Application ID.VONAGE_PRIVATE_KEY_PATH
: The file path to the private key associated with your Vonage Application. We recommend keeping it in the project root for simplicity in this example, but ensure appropriate file permissions in production.VONAGE_FROM_NUMBER
: The Vonage virtual phone number you will send SMS messages from. Use E.164 format (e.g.,14155552671
).
2. Implementing Core Functionality & API Layer
Now, let's write the code for our Express server and the SMS sending logic.
-
Edit
index.js
: Openindex.js
and add the following code:// index.js // 1. Import necessary modules const express = require('express'); const { Vonage } = require('@vonage/server-sdk'); const { Messages } = require('@vonage/messages'); // Import Messages class require('dotenv').config(); // Load environment variables from .env file // 2. Initialize Express app const app = express(); app.use(express.json()); // Middleware to parse JSON request bodies app.use(express.urlencoded({ extended: true })); // Middleware for URL-encoded bodies // 3. Initialize Vonage client // Ensure environment variables are loaded correctly const { VONAGE_APPLICATION_ID, VONAGE_PRIVATE_KEY_PATH, VONAGE_FROM_NUMBER } = process.env; if (!VONAGE_APPLICATION_ID || !VONAGE_PRIVATE_KEY_PATH || !VONAGE_FROM_NUMBER) { console.error(""Vonage credentials missing in .env file. Please check VONAGE_APPLICATION_ID, VONAGE_PRIVATE_KEY_PATH, and VONAGE_FROM_NUMBER.""); process.exit(1); // Exit if essential config is missing } const vonage = new Vonage({ applicationId: VONAGE_APPLICATION_ID, privateKey: VONAGE_PRIVATE_KEY_PATH }, { debug: false }); // Set debug: true for verbose SDK logging if needed // Initialize Messages using the options from the core Vonage client const vonageMessages = new Messages(vonage.options); // 4. Define the /send-sms endpoint app.post('/send-sms', async (req, res) => { console.log('Received POST request on /send-sms'); console.log('Request body:', req.body); // Basic Input Validation const { to, text } = req.body; if (!to || !text) { console.error('Missing `to` or `text` in request body'); return res.status(400).json({ success: false, message: 'Missing required fields: `to` (recipient phone number) and `text` (message content).' }); } // Ensure 'to' number is in a reasonable format (simple check) // Vonage expects E.164 format (e.g., 14155552671 without '+') for 'to' and 'from' // This regex checks for 10-15 digits after removing an optional leading '+' // Note: This is a basic check and doesn't fully validate E.164 globally. if (!/^\d{10,15}$/.test(to.replace(/^\+/, ''))) { console.error(`Invalid 'to' number format: ${to}`); return res.status(400).json({ success: false, message: 'Invalid recipient phone number format. Use digits only, optionally starting with + (e.g., 14155552671 or +14155552671).' }); } // Validate format of the 'from' number from environment variables if (!/^\d{10,15}$/.test(VONAGE_FROM_NUMBER.replace(/^\+/, ''))) { console.error(`Invalid 'VONAGE_FROM_NUMBER' format in .env: ${VONAGE_FROM_NUMBER}`); return res.status(500).json({ success: false, message: 'Server configuration error: Invalid sender phone number format.' }); } console.log(`Attempting to send SMS from ${VONAGE_FROM_NUMBER} to ${to}`); try { const resp = await vonageMessages.send({ message_type: ""text"", text: text, to: to, // Recipient number from: VONAGE_FROM_NUMBER, // Your Vonage number from .env channel: ""sms"" }); console.log('SMS submitted successfully:', resp); // Vonage Messages API returns message_uuid on success res.status(200).json({ success: true, message_uuid: resp.message_uuid }); } catch (error) { console.error('Error sending SMS via Vonage:', error); // Provide more specific feedback if possible let errorMessage = 'Failed to send SMS.'; if (error.response && error.response.data) { console.error('Vonage API Error details:', error.response.data); errorMessage = `Vonage API Error: ${error.response.data.title || 'Unknown error'} - ${error.response.data.detail || JSON.stringify(error.response.data)}`; } else if (error.message) { errorMessage = error.message; } res.status(500).json({ success: false, message: errorMessage, errorDetails: error.response?.data }); } }); // 5. Define a simple health check endpoint app.get('/health', (req, res) => { res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() }); }); // 6. Start the server only if this script is run directly (not required by a test runner) const port = process.env.PORT || 3000; if (require.main === module) { app.listen(port, () => { console.log(`Server listening on http://localhost:${port}`); console.log(`SMS sending endpoint available at POST http://localhost:${port}/send-sms`); console.log(`Health check available at GET http://localhost:${port}/health`); }); } // 7. Export the app instance for testing purposes module.exports = app;
Code Explanation:
- Imports: We import
express
, the coreVonage
class, theMessages
class from its specific package, anddotenv
. - Express Init: We create an Express application instance and use middleware to parse incoming JSON and URL-encoded request bodies.
- Vonage Init: We load environment variables using
dotenv.config()
. Crucially, we check if the necessary Vonage variables are present and exit if not. We then instantiate theVonage
client using theapplicationId
and the path to theprivateKey
. Authentication using Application ID and Private Key is recommended for server-to-server interactions with the Messages API. We then instantiate theMessages
service client, passing the configuration options from the coreVonage
instance. - /send-sms Endpoint:
- Defines a
POST
route at/send-sms
. - Uses
async/await
for cleaner handling of the asynchronous Vonage API call. - Performs basic validation to ensure the
to
(recipient number) andtext
(message body) fields are present in the request body. It also includes a simple format check for the phone numbers, allowing an optional+
and 10-15 digits. - Calls
vonageMessages.send()
with the required parameters:message_type
: Set to""text""
for SMS.text
: The message content from the request body.to
: The recipient's phone number from the request body.from
: Your Vonage virtual number loaded from the.env
file.channel
: Set to""sms""
.
- Uses a
try...catch
block for error handling. - On success, logs the response (which includes a
message_uuid
) and sends a 200 JSON response to the client. - On failure, logs the detailed error and sends a 500 JSON response with an error message.
- Defines a
- /health Endpoint: A simple
GET
endpoint to check if the server is running. - Server Start: Starts the Express server, listening on the port specified in
.env
(or defaulting to 3000). This is wrapped inif (require.main === module)
so it only runs when the script is executed directly, not when imported (e.g., by tests). - Export: Exports the
app
instance so it can be imported by test files.
- Imports: We import
3. API Endpoint Documentation
Here's how to interact with the API endpoint we created:
-
Endpoint:
POST /send-sms
-
Content-Type:
application/json
-
Request Body (JSON):
{ "to": "RECIPIENT_PHONE_NUMBER", "text": "Your SMS message content here." }
- Replace
RECIPIENT_PHONE_NUMBER
with the target phone number in E.164 format (e.g.,14155552671
or+14155552671
). - Replace
"Your SMS message content here."
with the desired message.
- Replace
-
Success Response (200 OK):
{ "success": true, "message_uuid": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" }
message_uuid
: A unique identifier assigned by Vonage to track the message status.
-
Error Response (400 Bad Request - Invalid Input):
{ "success": false, "message": "Missing required fields: `to` (recipient phone number) and `text` (message content)." }
-
Error Response (500 Internal Server Error - Vonage API Error):
{ "success": false, "message": "Vonage API Error: Invalid Credentials - Authentication failure", "errorDetails": { /* Raw error object from Vonage if available */ } }
Testing with curl
:
Replace placeholders with your actual recipient number and message.
curl -X POST http://localhost:3000/send-sms \
-H "Content-Type: application/json" \
-d '{
"to": "14155552671",
"text": "Hello from Node.js and Vonage!"
}'
4. Integrating with Vonage (Obtaining Credentials)
Follow these steps in your Vonage Dashboard to get the necessary credentials and configure your account:
- Sign Up/Log In: Access your Vonage API Dashboard.
- Create a Vonage Application:
- Navigate to ""Your applications"" in the left-hand menu.
- Click ""Create a new application"".
- Give your application a meaningful name (e.g., ""Node SMS Sender App"").
- Click ""Generate public and private key"". Crucially, save the
private.key
file that downloads immediately. You will need this file. Store it securely. The recommended location for this guide is the project root directory (vonage-sms-sender/private.key
). - Enable the ""Messages"" capability. You do not need to fill in the Status or Inbound URLs for sending SMS only, but they are required if you plan to receive delivery receipts or inbound messages later.
- Click ""Generate new application"".
- On the next screen, you will see your Application ID. Copy this value.
- Link Your Vonage Number:
- While still viewing your newly created application details, scroll down to the ""Link virtual numbers"" section.
- Find the Vonage virtual number you want to send SMS messages from.
- Click the ""Link"" button next to that number. If you don't have a number, you'll need to go to ""Numbers"" -> ""Buy numbers"" first.
- Copy the Vonage Number you just linked (use E.164 format, e.g.,
14155552671
).
- Configure API Settings (Optional but Recommended):
- Navigate to ""API Settings"" in the left-hand menu.
- Scroll down to ""SMS Settings"".
- Ensure ""Default SMS Setting"" is set to Messages API. This ensures consistency if you use other Vonage features. Click ""Save changes"" if you modify it.
- Update
.env
File:- Open your project's
.env
file. - Paste the Application ID you copied into the
VONAGE_APPLICATION_ID
field. - Ensure the
VONAGE_PRIVATE_KEY_PATH
points to the correct location where you saved theprivate.key
file (e.g.,./private.key
if it's in the project root). - Paste the Vonage Number you linked into the
VONAGE_FROM_NUMBER
field (use E.164 format).
- Open your project's
5. Error Handling and Logging
Our index.js
already includes basic error handling:
- Input Validation: Checks for the presence and basic format of
to
andtext
in the request, returning a 400 status code for invalid input. - Vonage API Errors: The
try...catch
block captures errors during thevonageMessages.send()
call. It logs the error to the console and attempts to return a meaningful error message and a 500 status code to the client. - Configuration Errors: Checks for missing environment variables on startup.
Enhancements for Production:
- Structured Logging: Replace
console.log
andconsole.error
with a dedicated logging library like Winston or Pino. This enables structured logging (e.g., JSON format), different log levels (debug, info, warn, error), and directing logs to files or external services. - Detailed Error Parsing: The current error handling attempts to parse Vonage's response. You can refine this further based on specific Vonage error codes or types documented in the Messages API Reference.
- Retry Mechanisms: For transient network issues or temporary Vonage API unavailability, implement a retry strategy with exponential backoff using libraries like
async-retry
. Wrap thevonageMessages.send()
call within the retry logic. Be cautious not to retry indefinitely or for errors that are clearly non-recoverable (like invalid credentials).
Example Logging Error Details:
When an error occurs, the console output might look like this:
Error sending SMS via Vonage: [Error: Request failed with status code 401] { ... detailed error object ... }
Vonage API Error details: {
type: 'https://developer.nexmo.com/api-errors/messages-olympia#unauthorised',
title: 'Unauthorized',
detail: 'You did not provide valid credentials',
instance: 'bf12a34b-c5d6-e7f8-a9b0-abcdef123456'
}
The corresponding JSON response would include this information.
6. Database Schema and Data Layer
This specific application focuses solely on sending an SMS via an API call and does not require a database.
If you were building a more complex system (e.g., tracking message history, managing contacts, scheduling messages), you would introduce a database (like PostgreSQL, MySQL, MongoDB) and a data layer (using an ORM like Prisma or Sequelize, or native drivers). This would involve:
- Defining schemas/models (e.g.,
MessageLog
,Contact
). - Setting up database connections.
- Implementing functions to interact with the database (e.g., saving message details after successful submission to Vonage).
7. Security Features
Security is paramount, especially when handling API keys and sending communications.
- Input Validation: We implemented basic checks. In production, use robust validation libraries like Joi or express-validator to define strict schemas for request bodies, validating data types, formats (E.164 for phone numbers), and length limits.
- Input Sanitization: While less critical for the
text
field when sending SMS (as it's not typically rendered as HTML), be mindful if user-provided input is used elsewhere. Libraries likeDOMPurify
(for HTML) or simply ensuring correct data types can help. - API Credential Security:
- NEVER hardcode API keys, Application IDs, or private key content directly in your source code.
- Use environment variables (
.env
locally, secure configuration management in deployment). - Ensure
.env
andprivate.key
are listed in.gitignore
. - Secure the
private.key
file with appropriate file system permissions (restrict read access). In production, consider loading the key content directly from a secure environment variable instead of a file path.
- Rate Limiting: Protect your API endpoint from abuse and brute-force attacks by implementing rate limiting. Use middleware like express-rate-limit.
// Example Rate Limiting (add near the top of index.js) const rateLimit = require('express-rate-limit'); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Limit each IP to 100 requests per windowMs standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers legacyHeaders: false, // Disable the `X-RateLimit-*` headers }); // Apply the rate limiting middleware to API calls only app.use('/send-sms', limiter);
- HTTPS: Ensure your application is served over HTTPS in production to encrypt traffic. Deployment platforms often handle this.
- Authentication/Authorization (Optional): The current API is open. For protected use, implement an authentication mechanism (e.g., requiring a static API key in headers, JWT tokens, OAuth) to ensure only authorized clients can send SMS.
8. Handling Special Cases
- Phone Number Formatting: Vonage strongly prefers the E.164 format for
to
andfrom
numbers (e.g.,14155552671
for a US number,447700900000
for a UK number). Our basic validation encourages this by allowing an optional+
followed by digits. Avoid dashes, spaces, or parentheses in the final number sent to Vonage. - Character Limits: Standard SMS messages have character limits (160 for GSM-7 encoding, 70 for UCS-2 used for non-Latin characters). Longer messages are split into multiple segments, which may incur additional costs. Vonage handles segmentation automatically, but be mindful of message length for cost and user experience.
- International Sending: Sending SMS internationally is supported but may have different pricing and regulations depending on the destination country. Ensure your Vonage account is enabled for international sending if needed. Test thoroughly.
- ""From"" Number: You must use a Vonage number that is linked to your Vonage Application and capable of sending SMS. Using other numbers will result in errors.
- Trial Account Restrictions: See Section 11 (Troubleshooting).
9. Performance Optimizations
For this simple sender, performance bottlenecks are unlikely unless sending extremely high volumes.
- Asynchronous Operations: Node.js and the Vonage SDK operate asynchronously, preventing the API call from blocking the server. This is inherently efficient.
- High Volume Sending: If you need to send thousands of messages rapidly, consider:
- Queuing: Instead of calling the Vonage API directly in the request handler, push message details onto a message queue (like RabbitMQ, Redis Streams, or AWS SQS). Have separate worker processes consume from the queue and send the SMS messages. This decouples the API response from the sending process and allows for better scaling and rate management.
- Concurrency Control: Manage how many concurrent requests your application makes to the Vonage API to stay within any rate limits imposed by Vonage or your own infrastructure.
10. Monitoring, Observability, and Analytics
- Health Checks: The
/health
endpoint provides a basic check. Production systems often require more sophisticated health checks verifying dependencies (e.g., can the Vonage client initialize?). - Logging: Centralized and structured logging (as mentioned in Section 5) is crucial for monitoring application behavior and diagnosing issues.
- Performance Metrics: Monitor key metrics like request latency (especially for the
/send-sms
endpoint), request rate, and error rates using Application Performance Monitoring (APM) tools (e.g., Datadog, New Relic, Dynatrace). Node.js libraries often integrate with these tools. - Error Tracking: Integrate dedicated error tracking services (e.g., Sentry, Bugsnag, Rollbar). These capture detailed error information (stack traces, request context) and provide alerts.
// Conceptual Sentry Integration (requires installing @sentry/node and @sentry/tracing) // const Sentry = require('@sentry/node'); // const Tracing = require('@sentry/tracing'); // Sentry.init({ dsn: ""YOUR_SENTRY_DSN"", tracesSampleRate: 1.0, integrations: [new Sentry.Integrations.Http({ tracing: true }), new Tracing.Integrations.Express({ app })] }); // app.use(Sentry.Handlers.requestHandler()); // app.use(Sentry.Handlers.tracingHandler()); // // Your routes here... // app.use(Sentry.Handlers.errorHandler());
- Vonage Dashboard: Utilize the Vonage Dashboard's analytics sections to monitor message delivery rates, costs, and usage patterns.
11. Troubleshooting and Caveats
Non-Whitelisted Destination
Error:- Cause: You are using a Vonage trial account, which requires you to explicitly approve (whitelist) phone numbers you want to send messages to.
- Solution:
- Go to your Vonage Dashboard.
- Navigate to "Getting started" or look for a "Test numbers" section (the exact location might vary slightly).
- Find the area to add test numbers. Enter the recipient phone number(s) you want to test with.
- You'll usually need to verify ownership via an SMS or voice call code sent to that number.
- Once verified, you can send messages to that specific number from your trial account.
Unauthorized
/Invalid Credentials
Error (401):- Cause: Incorrect
VONAGE_APPLICATION_ID
or invalid/missingprivate.key
file referenced byVONAGE_PRIVATE_KEY_PATH
in your.env
file. The private key might also not be correctly associated with the Application ID in the Vonage system. - Solution: Double-check the Application ID in your dashboard and
.env
. Verify the path toprivate.key
is correct and the file exists and is readable by your Node.js process. Ensure you generated the key pair for this specific application.
- Cause: Incorrect
Invalid Sender
/ Cannot useFROM
number (4xx Error):- Cause: The
VONAGE_FROM_NUMBER
in your.env
file is either not a valid Vonage number, not linked to the specific Vonage Application you are using (viaVONAGE_APPLICATION_ID
), or not SMS-capable. - Solution: Verify the number in your Vonage Dashboard under "Numbers". Ensure it's linked to the correct application (see Section 4, Step 3). Check the number's capabilities.
- Cause: The
Insufficient Funds
Error:- Cause: Your Vonage account balance is too low to cover the cost of the SMS.
- Solution: Add credit to your Vonage account.
- Invalid
to
Number Format:- Cause: The recipient number passed in the request body is not in the expected E.164 format after basic processing.
- Solution: Ensure the client sends the number correctly (e.g.,
14155552671
or+14155552671
).
- Firewall Issues: Ensure your server can make outbound HTTPS requests to
*.vonage.com
(specifically the Messages API endpoints). - SDK Version Compatibility: Issues can arise if mixing incompatible versions of Vonage SDK components or if using a very outdated version. Stick to recent, stable releases. Check the
@vonage/server-sdk
and@vonage/messages
documentation for compatibility notes if issues persist.
12. Deployment and CI/CD
Deploying this Node.js application involves running it on a server or platform.
General Steps:
- Choose a Platform: Options include Heroku, Vercel, AWS (EC2, Lambda, Fargate, Elastic Beanstalk), Google Cloud (App Engine, Cloud Run), Azure App Service, DigitalOcean Apps, etc.
- Environment Variables: Configure the production environment variables (
PORT
,VONAGE_APPLICATION_ID
,VONAGE_PRIVATE_KEY_PATH
,VONAGE_FROM_NUMBER
,NODE_ENV=production
) securely on your chosen platform. Do not commit.env
to Git. - Private Key Handling: This is critical.
- Option A (Recommended): Load the content of the
private.key
file into a secure environment variable (e.g.,VONAGE_PRIVATE_KEY_CONTENT
). Modifyindex.js
to use this content directly:// index.js - modification for key content in env var const vonage = new Vonage({ applicationId: process.env.VONAGE_APPLICATION_ID, privateKey: process.env.VONAGE_PRIVATE_KEY_CONTENT // Use content directly }); // Re-initialize Messages with the updated Vonage options const vonageMessages = new Messages(vonage.options);
- Option B: Securely transfer the
private.key
file to the server during deployment (e.g., using SCP, CI/CD secure files, platform-specific secrets management) and ensureVONAGE_PRIVATE_KEY_PATH
points to its location on the server. Restrict file permissions. Avoid committing the key file to Git.
- Option A (Recommended): Load the content of the
- Build Step (if applicable): If using TypeScript or a build process, run the build command.
- Start Command: Configure the platform to start the application using
node index.js
. Update thestart
script inpackage.json
:// package.json ""scripts"": { ""start"": ""node index.js"", ""test"": ""jest"" // Example if using Jest for tests },
- HTTPS: Ensure the platform provides or is configured for HTTPS.
Example: Basic Dockerfile
# Use an official Node.js runtime as a parent image
FROM node:18-slim
# Set the working directory in the container
WORKDIR /usr/src/app
# Copy package.json and package-lock.json (or yarn.lock)
COPY package*.json ./
# Install app dependencies for production
# Use --omit=dev if you have devDependencies you don't need in production
RUN npm install --omit=dev
# Bundle app source
COPY . .
# Make port 3000 available to the world outside this container (adjust if needed)
EXPOSE 3000
# Define the command to run your app
CMD [ ""node"", ""index.js"" ]
# Note: This Dockerfile assumes you handle VONAGE env vars and the private key
# externally (e.g., via docker run -e flags, docker-compose, K8s secrets)
# DO NOT copy the .env or private.key file into the image directly.
CI/CD Pipeline (Conceptual - e.g., GitHub Actions):
# .github/workflows/deploy.yml
name: Deploy Vonage SMS Sender
on:
push:
branches: [ main ] # Trigger on push to main branch
jobs:
build-and-deploy: # Renamed job for clarity
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4 # Use latest major version
- name: Set up Node.js
uses: actions/setup-node@v4 # Use latest major version
with:
node-version: '18'
cache: 'npm' # Enable npm caching
- name: Install Dependencies
run: npm ci # Use ci for cleaner installs in CI
- name: Run Tests (Optional but Recommended)
run: npm test
env: # Provide dummy env vars for tests if needed, avoid real secrets
VONAGE_APPLICATION_ID: test-app-id
VONAGE_PRIVATE_KEY_PATH: /dev/null # Or path to a dummy key if needed
VONAGE_FROM_NUMBER: 15555555555
# Add steps here to build (if needed) and deploy to your platform
# Example: Build Docker image and push to registry, deploy to cloud service
# This highly depends on your chosen platform.
# Ensure you configure secrets (VONAGE_APPLICATION_ID, VONAGE_PRIVATE_KEY_CONTENT, etc.)
# in GitHub repository secrets and pass them securely to the deployment steps.
- name: Example Placeholder - Deploy Step
run: echo ""Deploying application..."" # Replace with actual deployment commands
Rollback: Deployment platforms usually offer mechanisms to roll back to previous versions if a deployment introduces issues. Familiarize yourself with your platform's rollback procedures.