Frequently Asked Questions
Use the Plivo API and Node.js SDK within an Express app. Create a POST /send-sms endpoint that accepts recipient number and message text, then uses the Plivo SDK to send the SMS via your Plivo account.
Plivo is a cloud communications platform that provides the SMS sending functionality. The Node.js app interacts with Plivo's API using the Plivo Node.js SDK, abstracting away low-level API details.
Express.js simplifies the process of setting up routes and handling HTTP requests in the Node.js application. It provides a straightforward way to create the /send-sms API endpoint.
For sending SMS in the US or Canada, you must purchase a Plivo phone number. For other countries, you might be able to use a registered Alphanumeric Sender ID, but check Plivo's guidelines as requirements vary by country.
Trial accounts typically restrict sending to verified "Sandbox" numbers within your Plivo console. You'll need a full Plivo account to send to regular numbers.
Initialize a Node.js project using npm init, then install the 'express', 'plivo', and 'dotenv' packages. Create server.js for the main application logic, and a routes/sms.js file for the API endpoint handler.
The .env file stores sensitive credentials like your Plivo Auth ID, Auth Token, and Sender Number. The 'dotenv' package loads these into process.env, making them accessible to your application.
Implement error handling for invalid inputs, missing credentials, and Plivo API errors. Use try...catch blocks to manage Plivo API calls, logging errors and sending appropriate responses to the client.
Use the E.164 international number format, which includes a '+' prefix followed by the country code and phone number (e.g., +12025550100).
Use environment variables (.env) for credentials. Implement robust input validation and consider rate limiting using a library like 'express-rate-limit' and security headers with 'helmet'.
The example code sends to one recipient per request. For multiple recipients, loop through the recipient list in your route handler and call client.messages.create for each, or use Plivo's bulk messaging API.
Check the error details in the Plivo API response and logs. Retry the request for transient errors (e.g. network or 5xx Plivo errors) using a retry mechanism with exponential backoff.
Log incoming request details, attempts to send SMS, Plivo responses (including 'messageUuid'), and detailed errors for debugging and auditing purposes. Use a logging library for production.
Use 'curl' or Postman to send requests to your local server or deployed API. Test both valid requests and error scenarios, including missing inputs, bad formats, and invalid credentials.
Send SMS Messages with Node.js, Express, and Plivo
Learn how to send SMS messages programmatically using Node.js, Express.js, and the Plivo messaging API. This comprehensive tutorial walks you through building a production-ready SMS application from scratch, covering authentication, error handling, security, deployment, and 10DLC compliance for US messaging.
By the end of this guide, you'll have a fully functional REST API endpoint that can send text messages to any phone number worldwide using Plivo's cloud communications platform. Perfect for implementing two-factor authentication (2FA), transactional notifications, appointment reminders, or marketing campaigns.
Framework Compatibility Note (2025): This guide supports both Express 4.x and Express 5.x. Express 5.1.0 became the default on npm as of March 31, 2025, and requires Node.js 18 or higher. Express 5 includes breaking changes:
req.param()
is removed (usereq.params
,req.body
, orreq.query
explicitly), and promise rejections automatically forward to error-handling middleware. If using Express 5, review the Express 5 migration guide.What You'll Build: SMS API Project Overview
Goal: Create a secure and robust Node.js Express API endpoint (
POST /send-sms
) that accepts a recipient phone number and message body, then uses the Plivo API to send the SMS.Problem Solved: Provides a backend service to programmatically send SMS messages, abstracting direct Plivo API interaction behind a simple web service.
Real-World Use Cases:
Technologies:
^4.x
.env
file intoprocess.env
.^16.0.0
or laterSystem Architecture:
Prerequisites:
curl
or Postman: For testing the API endpoint.10DLC Registration Process (US Only):
Common 10DLC Issues:
Trial Account Limitations: Plivo trial accounts can typically only send messages to phone numbers verified within your Plivo console (Sandbox Numbers).
SMS Pricing (US, 2025): Plivo charges $0.0055 per outbound SMS segment via long code, plus carrier surcharges ranging from $0.0030 (AT&T, T-Mobile) to $0.0050 (US Cellular, other carriers) per SMS for 10DLC-registered traffic. Check Plivo's SMS pricing page for current rates and international pricing.
Cost Calculation Examples:
1. Setting up Your Node.js Express Project
Initialize your Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal and create a new directory for your project, then navigate into it.
Initialize Node.js Project: Create a
package.json
file to manage project dependencies and scripts.(The
-y
flag accepts default settings)Install Dependencies: Install Express for the web server, the Plivo SDK to interact with their API, and
dotenv
to manage environment variables.Dependency Versions (2025):
express@^5.1.0
: Latest stable Express 5.x (use^4.21.2
for Express 4.x)plivo@^4.67.1
: Current Plivo SDKdotenv@^16.4.5
: Environment variable managementCreate Project Structure: Set up a basic structure for clarity.
server.js
: The main entry point for your application.routes/
: Directory to organize route handlers..env
: File to store sensitive credentials (API keys, etc.). Never commit this file to version control..gitignore
: Specifies intentionally untracked files that Git should ignore.Configure
.gitignore
: Addnode_modules
and.env
to prevent committing them. Open.gitignore
and add:Set up Basic Express Server (
server.js
): Openserver.js
and add the initial Express setup.require('dotenv').config();
: Loads variables from.env
. Call this early.express.json()
andexpress.urlencoded()
: Middleware needed to parse incoming request bodies.process.env.PORT || 3000
: Allows configuring the port via environment variables, essential for deployment platforms.2. How to Send SMS with Plivo API: Implementing Core Functionality
Create the logic to interact with the Plivo API using their Node.js SDK.
Create SMS Route File: Inside the
routes
directory, create a file namedsms.js
.Implement the Sending Logic (
routes/sms.js
): This file defines the router and the handler for your/send-sms
endpoint.express
andplivo
.express.Router()
.process.env
. Add checks to ensure they exist.POST /send-sms
handler usesasync/await
for cleaner asynchronous code.to
andtext
are provided andto
roughly matches E.164 format. A note about using better libraries likelibphonenumber-js
is included.client.messages.create()
sends the SMS. Key parameters:src
(sender),dst
(recipient),text
(message content). Optional parameters includetype
,url
(delivery receipt callback),method
, andlog
.Mount the Router in
server.js
: Uncomment and add the lines inserver.js
to use the router you just created.Now, requests to
POST /api/send-sms
will be handled by yourroutes/sms.js
logic.3. Building and Testing Your SMS API Endpoint
You've already implemented the core API endpoint (
POST /api/send-sms
) in the previous step. This section details its usage and provides testing examples.API Endpoint Specification:
POST
/api/send-sms
application/json
Request Body Parameters:
to
+14155552671
text
Hello from Plivo!
Response Status Codes:
Example
curl
Request:Replace placeholders with your actual server address, recipient number, and message.
Example Success Response (HTTP 202 Accepted):
Example Error Response (HTTP 400 Bad Request – Missing Field):
Example Error Response (HTTP 400 Bad Request – Invalid Number Format):
Example Error Response (HTTP 500 Internal Server Error – Plivo API Failure):
4. Plivo Authentication: Configuring Your API Credentials
Proper configuration and secure handling of credentials are critical.
Obtain Plivo Credentials and Sender Number:
+12025551234
).Configure Environment Variables (
.env
file): Open the.env
file in your project's root directory and add your credentials. Replace the placeholder values.PLIVO_AUTH_ID
: Your unique authentication identifier.PLIVO_AUTH_TOKEN
: Your secret authentication token. Treat this like a password.PLIVO_SENDER_NUMBER
: The number or ID messages will appear to come from. Must be a valid Plivo number (for US/Canada) or a registered Sender ID where applicable.Load Environment Variables: The
require('dotenv').config();
line at the top ofserver.js
loads these variables intoprocess.env
, making them accessible throughout your application (as seen inroutes/sms.js
).Security: The
.env
file keeps your sensitive credentials out of your source code. Ensure your.gitignore
file includes.env
to prevent accidentally committing it. In production environments, set these variables directly in the deployment platform's configuration settings, not via a.env
file.Platform-Specific Configuration:
heroku config:set PLIVO_AUTH_ID=xxx
)-e
flag or docker-compose.ymlFallback Mechanisms: For this simple guide, there's no fallback. In a production system requiring high availability, consider:
5. Error Handling Best Practices for SMS Applications
Robust error handling and logging are crucial for debugging and reliability.
Error Handling Strategy:
client.messages.create()
call. Log the detailed error. Return an appropriate HTTP status code (often 500 Internal Server Error, or useerror.statusCode
if Plivo's SDK provides it) and a JSON error message including details from the Plivo error.try...catch
blocks to prevent unhandled promise rejections from crashing the server.Implement Global Error Handler: Add this middleware at the end of
server.js
, after all routes:Logging:
console.log
for successful operations and Plivo responses, andconsole.error
for errors. This is suitable for development.Example Winston Setup:
Usage:
Retry Mechanisms:
Sending an SMS is often idempotent from Plivo's side (sending the same request usually doesn't result in duplicate messages if the first was accepted), but network issues could prevent the request from reaching Plivo.
For critical messages, implement a simple retry strategy with exponential backoff for network errors or specific transient Plivo errors (e.g., 5xx status codes). Libraries like
async-retry
can help.Example (Conceptual):
Caution: Don't retry indefinitely or for errors that won't resolve (like invalid credentials or invalid recipient numbers).
Common Plivo Error Codes:
to
ortext
.to
number formats..env
with incorrectPLIVO_AUTH_ID
orPLIVO_AUTH_TOKEN
to test authentication failures.PLIVO_SENDER_NUMBER
to an invalid one.6. Database Schema and Data Layer
For this specific guide (only sending an SMS via an API call)_ a database is not strictly required.
However_ in a real-world application_ add a database (like PostgreSQL_ MySQL_ MongoDB) to:
messageUuid
_ recipient_ sender_ timestamp_ status (initially "queued"_ potentially updated via webhooks)_ and message content. This aids auditing and tracking.Example Database Schema (PostgreSQL):
Field Descriptions:
id
plivo_message_uuid
recipient_number
sender_id
message_text
status
error_message
created_at
updated_at
delivered_at
(Full implementation details omitted as they are beyond the scope of this basic SMS sending guide).
7. Security Best Practices for SMS APIs
Enhance the security of your API endpoint.
Input Validation and Sanitization:
to
andtext
. For production_ use a robust validation library likejoi
orexpress-validator
.Example with Joi:
Common Vulnerabilities & Protections:
X-API-Key
) or using more robust methods like JWT.X-Content-Type-Options
_Referrer-Policy
_Strict-Transport-Security
_X-Frame-Options
to mitigate common web vulnerabilities.Implement Rate Limiting: Use a library like
express-rate-limit
.Install:
npm install express-rate-limit
Apply in
server.js
:Adjust
windowMs
andmax
according to your expected usage and security requirements.Implement Basic Security Headers: Use the
helmet
middleware.Install:
npm install helmet
Apply in
server.js
:helmet()
applies several default security-related HTTP headers.Protecting API Keys: Already covered by using
.env
and.gitignore
. Ensure production environments use secure configuration management.Testing for Vulnerabilities:
npm audit
).8. Understanding SMS Message Format and Compliance
E.164 Format: Strictly enforce the
+
prefix and country code format forto
numbers. Plivo requires this. Considerlibphonenumber-js
for robust parsing and validation, as it understands nuances like variable number lengths per country.Character Encoding (GSM vs. Unicode):
Plivo handles encoding automatically based on the
text
content. Longer messages or messages with Unicode characters split into multiple segments (concatenated on the recipient's device) and billed accordingly. See Plivo's Encoding and Concatenation guide.Message Length Examples:
Sender ID Rules: US/Canada requires a Plivo number. Other countries have varying rules for numeric vs. alphanumeric sender IDs, often requiring pre-registration. Using an invalid or unregistered sender ID will cause message delivery failure. Check Plivo's country-specific SMS guidelines.
Trial Account Limitations: Sending is restricted to verified "Sandbox" numbers.
Opt-Out Handling: Regulations (like TCPA in the US) require handling STOP and HELP keywords. Plivo can manage standard opt-outs automatically for long codes and Toll-Free numbers if you configure this in the console. Ensure compliance with local regulations.
Compliance Requirements by Region:
9. Performance Optimization for High-Volume SMS
For this simple single-message API, major optimizations are usually unnecessary. However, for higher volume:
async/await
maintains this benefit with cleaner syntax.Example BullMQ Queue Setup:
k6
,Artillery
, orApacheBench
(ab) to simulate concurrent users and identify bottlenecks under load. Monitor CPU, memory, and response times during tests.Example k6 Load Test:
node --prof
) or tools like Clinic.js to identify performance hotspots in your code.10. Monitoring and Observability for SMS Applications
For production readiness:
Health Checks: Add a simple health check endpoint that verifies basic application status.
Performance Metrics: Monitor key metrics like request latency, request rate (RPM), error rates (4xx, 5xx), and resource usage (CPU, memory). Tools like Prometheus/Grafana, Datadog APM, or New Relic can track these.
Example Prometheus Metrics:
Complete Sentry Integration:
console.log
with a structured logging library (Winston, Pino) that supports log levels, JSON formatting, and multiple transports (console, files, external services).Deploying Your SMS Application to Production
Environment Configuration: Use environment-specific
.env
files or platform configuration (Heroku Config Vars, AWS Parameter Store, etc.) to manage credentials and settings across development, staging, and production.Process Management: Use a process manager like PM2 or systemd to keep your Node.js application running, handle crashes with automatic restarts, and manage multiple instances for load balancing.
Example PM2 Configuration:
Load Balancing: Deploy multiple instances of your application behind a load balancer (NGINX, AWS ALB, etc.) to distribute traffic and ensure high availability.
SSL/TLS: Always use HTTPS in production. Obtain SSL certificates from Let's Encrypt or your cloud provider.
Security Hardening: Review OWASP Top 10 vulnerabilities, implement proper input validation, use security headers (helmet), enable rate limiting, and keep dependencies updated.
Monitoring and Alerting: Set up alerts for critical metrics like high error rates, slow response times, or service downtime. Use tools like PagerDuty, Opsgenie, or cloud provider alerting.
Backup and Disaster Recovery: If you add a database, implement regular backups and test your disaster recovery procedures.
Cost Optimization: Monitor your Plivo usage and costs. Implement message queuing for batch sends to optimize throughput. Consider caching frequently accessed data to reduce API calls.
Platform-Specific Deployment:
Heroku:
AWS Elastic Beanstalk:
Docker:
Related Resources
This comprehensive guide provides everything you need to send SMS messages with Plivo, Node.js, and Express. Build upon these patterns to create more sophisticated messaging features tailored to your application's needs.