Tutorials

Receive SMS with Plivo in Node.js and Express: Two-Way Messaging Guide

Learn how to receive SMS messages in Node.js using Plivo and Express. Complete tutorial covering webhook setup, signature validation, auto-replies, and deployment for production two-way messaging.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 7, 2026 β€’ 20 min read

Developer Quick-Start: Learn how to receive SMS messages in Node.js using Plivo and Express. Complete tutorial covering webhook setup, signature validation, auto-replies, and deployment for production two-way messaging. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.

Learn how to receive SMS messages in Node.js using Plivo's SMS API and Express framework. This comprehensive guide walks you through building a production-ready application that handles inbound SMS webhooks, validates signatures, and sends automated repliesβ€”perfect for customer support bots, appointment confirmations, and interactive messaging systems.

When someone sends an SMS to your Plivo phone number, Plivo forwards it to your Express application via HTTP webhook. You'll learn how to set up your project, configure the webhook endpoint, process incoming messages, generate XML responses, secure your application, and deploy it to production. By the end, you'll have a functional Express application that receives SMS messages and responds automatically.

Common Use Cases

Use Case Complexity Implementation Time
Auto-reply with keywords (HELP, STOP) Simple 1–2 hours
Appointment confirmation system Moderate 4–6 hours
Customer support bot with conversation state Complex 2–3 days
Order tracking notifications Moderate 3–5 hours

Technologies Used

  • Node.js: A JavaScript runtime environment for building server-side applications. Recommended: Node.js v22 LTS (Long Term Support began October 2024, maintained until April 2027).
  • Express.js: A minimal and flexible Node.js web application framework (v4.16+ includes necessary body parsing middleware built-in via express.urlencoded() and express.json()).
  • Plivo: A cloud communications platform providing SMS API services.
  • Plivo Node.js SDK: Simplifies interaction with the Plivo API and XML generation. Latest version: 4.74.0 (as of January 2025).
  • ngrok (for development): A tool to expose local development servers to the internet. Note: The free tier includes 1 static domain (available since August 2023), eliminating the need to update URLs constantly during development sessions.
  • dotenv: A module to load environment variables from a .env file.

System Architecture

graph LR
    A[End User] -- Sends SMS --> B(Plivo Phone Number);
    B -- Forwards SMS via HTTP POST --> C{Your Express App Webhook};
    C -- Processes Request --> C;
    C -- Generates Plivo XML Response --> C;
    C -- Sends XML Response --> B;
    B -- Sends Reply SMS --> A;

    style C fill:#f9f,stroke:#333,stroke-width:2px

How It Works

  1. User sends SMS – An end user texts your Plivo phone number
  2. Plivo forwards webhook – Plivo sends an HTTP POST request to your Express app's /receive\_sms endpoint
  3. App processes message – Your application validates the signature, processes the message, and generates a response
  4. XML response – Your app returns Plivo XML containing the reply message
  5. Plivo sends reply – Plivo delivers your reply SMS to the user

Prerequisites

Before you can receive SMS in Node.js with Plivo, you'll need:

  • A Plivo account (Sign up for free).
  • An SMS-enabled Plivo phone number (Purchase via the Plivo console: Phone Numbers > Buy Numbers).
  • Node.js (v22 LTS recommended, minimum v18+) and npm (or yarn) installed on your system.
  • Basic understanding of JavaScript and Node.js.
  • ngrok installed for local development testing (Download ngrok).

1. Setting Up Your Node.js Project to Receive SMS

Create a new Node.js project and install the dependencies needed to receive SMS messages with Plivo and Express.

  1. Create Project Directory: Create a new directory for your project, then navigate into it.
   mkdir plivo-node-sms-inbound
   cd plivo-node-sms-inbound
  1. Initialize Node.js Project: Initialize the project using npm to create a package.json file.
   npm init -y

The -y flag accepts the default settings.

  1. Install Dependencies: Install Express for the web server, the Plivo Node.js SDK, and dotenv for managing environment variables. Modern Express (v4.16+) includes the necessary middleware for parsing URL-encoded bodies, so body-parser is no longer required separately.
   npm install express plivo dotenv
  • express: The web framework. Includes express.urlencoded() middleware.
  • plivo: The official Plivo Node.js SDK.
  • dotenv: Loads environment variables from a .env file into process.env.
  1. Create Project Structure: Create the basic files and directories.
   touch server.js .env .gitignore
  • server.js: Contains your main application code.
  • .env: Stores sensitive credentials like your Plivo Auth Token. Never commit this file to version control.
  • .gitignore: Specifies intentionally untracked files that Git should ignore.
  1. Configure .gitignore: Add node_modules and .env to your .gitignore file to prevent committing them.
   # .gitignore

   node_modules/
   .env
  1. Set Up Environment Variables (.env): Add your Plivo Auth ID and Auth Token for webhook validation. Find these on your Plivo Console dashboard.

.env

   # .env

   # Plivo Credentials (Find on Plivo Console Dashboard)
   PLIVO_AUTH_ID=YOUR_PLIVO_AUTH_ID
   PLIVO_AUTH_TOKEN=YOUR_PLIVO_AUTH_TOKEN

   # Server Configuration
   PORT=3000
  • Replace YOUR\_PLIVO\_AUTH\_ID and YOUR\_PLIVO\_AUTH\_TOKEN with your actual credentials.
  • PORT: The port your local server will run on.

2. Creating Your Express SMS Webhook Handler

Build the Express application to receive SMS webhooks from Plivo. When someone texts your Plivo number, Plivo sends an HTTP POST request to your webhook endpoint. This section shows you how to handle incoming messages and send automated replies.

Understanding How Plivo SMS Webhooks Work

A webhook is an HTTP callback that Plivo uses to notify your application about incoming messages. When Plivo receives an SMS at your number, it immediately sends an HTTP POST request to your configured Message URL. Your Express app processes the request and responds with XML instructions telling Plivo what to do nextβ€”such as sending a reply SMS back to the sender.

server.js:

require('dotenv').config();

const express = require('express');
const plivo = require('plivo');
const crypto = require('crypto');

const app = express();
const port = process.env.PORT || 3000;

app.use(express.urlencoded({ extended: true }));

const validatePlivoSignature = (req, res, next) => {
    const signature = req.header('X-Plivo-Signature-V3');
    const nonce = req.header('X-Plivo-Signature-V3-Nonce');



    const url = req.protocol + '://' + req.get('host') + req.originalUrl;
    const method = req.method;

    if (!signature || !nonce) {
        console.warn('Missing Plivo signature headers');
        return res.status(400).send('Missing signature headers');
    }

    try {


        const valid = plivo.validateV3Signature(method, url, nonce, process.env.PLIVO_AUTH_TOKEN, signature);

        if (valid) {
            console.log('Plivo signature validation successful.');
            next();
        } else {
            console.warn('Invalid Plivo signature.');
            return res.status(403).send('Invalid signature');
        }
    } catch (error) {
        console.error('Error during Plivo signature validation:', error);
        return res.status(500).send('Signature validation error');
    }
};

app.post('/receive_sms', validatePlivoSignature, (req, res) => {

    const from_number = req.body.From;
    const to_number = req.body.To;
    const text = req.body.Text;
    const message_uuid = req.body.MessageUUID;

    console.log(`Message received on ${to_number} from ${from_number}: "${text}" (UUID: ${message_uuid})`);




    let reply_text = `Thank you for your message! We received: "${text}"`;
    if (text && text.toLowerCase().includes('help')) {
        reply_text = `Need help? Contact support@example.com or call 1-800-555-HELP.`;
    } else if (text && text.toLowerCase().includes('stop')) {
        reply_text = `You have been unsubscribed. No more messages will be sent.`;

    }




    const response = new plivo.Response();


    const params = {
        src: to_number,
        dst: from_number
    };
    response.addMessage(reply_text, params);



    const xmlResponse = response.toXML();
    console.log(`Sending XML Response:\n`, xmlResponse);

    res.setHeader('Content-Type', 'application/xml');
    res.status(200).send(xmlResponse);

});

app.get('/health', (req, res) => {
    res.status(200).send('OK');
});

if (require.main === module) {
    app.listen(port, () => {
        console.log(`Server running on port ${port}`);
        console.log(`Plivo Auth ID: ${process.env.PLIVO_AUTH_ID ? 'Loaded' : 'MISSING!'}`);
        console.log(`Plivo Auth Token: ${process.env.PLIVO_AUTH_TOKEN ? 'Loaded' : 'MISSING!'}`);
        console.log('Make sure ngrok is running and pointed to this port for development testing.');
        console.log(`Webhook URL should be configured in Plivo as: http://<your-ngrok-url>/receive_sms`);
    });
}

module.exports = app;

Code Explanation

  1. Load Environment Variables: require('dotenv').config() loads variables from .env.
  2. Import Dependencies: Imports Express, the Plivo SDK, and Node's crypto module (needed internally by the SDK's validation function).
  3. Initialize App: Creates the Express application instance.
  4. Middleware:
  • express.urlencoded: Parses the incoming webhook data from Plivo using Express's built-in middleware.
  • validatePlivoSignature: Crucial security middleware. It verifies that incoming requests genuinely originated from Plivo using the X-Plivo-Signature-V3 header, a nonce, your Auth Token, and the request details. This prevents attackers from spoofing requests to your webhook. It's applied only to the /receive\_sms route. A note about potential URL reconstruction issues behind proxies is included.
  1. Webhook Route (/receive_sms):
  • This endpoint (using HTTP POST) is what Plivo calls when an SMS arrives.
  • It first runs the validatePlivoSignature middleware.
  • It extracts relevant information (From, To, Text, MessageUUID) from req.body.
  • Includes a placeholder for your business logic using template literals for replies.
  1. Generate Plivo XML:
  • Creates a plivo.Response object.
  • Uses response.addMessage(reply\_text, params) to add a <Message> tag to the XML. This tag instructs Plivo to send an SMS reply.
  • src (source) is your Plivo number (to\_number from the incoming message).
  • dst (destination) is the original sender's number (from\_number).
  1. Send XML Response:
  • Converts the Plivo response object to an XML string using response.toXML().
  • Sets the Content-Type header to application/xml.
  • Sends the XML back to Plivo with a 200 OK status. Plivo processes this XML to send the reply SMS.
  1. Start Server: Listens on the configured port, but only when server.js is executed directly (not when required by tests).
  2. Export App: The app object is exported so it can be imported by testing frameworks like supertest.

3. Building a Complete API Layer

In this specific scenario, the "API" is the single webhook endpoint (/receive_sms) that Plivo interacts with. We've already implemented:

  • Authentication/Authorization: Handled via Plivo's webhook signature validation (validatePlivoSignature middleware). Only requests signed correctly with your Plivo Auth Token are processed.
  • Request Validation: Basic validation happens via signature checking. Add more specific validation (e.g., checking expected fields, data types) within the /receive\_sms route handler if needed.
  • API Endpoint Documentation:
  • Endpoint: /receive\_sms
  • Method: POST
  • Content-Type (Request): application/x-www-form-urlencoded
  • Headers (Required from Plivo): X-Plivo-Signature-V3, X-Plivo-Signature-V3-Nonce
  • Request Body Parameters (from Plivo):
  • From: Sender's phone number (E.164 format).
  • To: Your Plivo number receiving the message (E.164 format).
  • Text: The content of the SMS message.
  • Type: sms
  • MessageUUID: Unique identifier for the incoming message.
  • (Other potential parameters like Encoding, ParentMessageUUID, etc. – see Plivo docs)
  • Response Content-Type: application/xml
  • Response Body (Example Success):
    <?xml version="1.0" encoding="utf-8"?>
    <Response>
       <Message src="+14155551212" dst="+14155559876">Thank you for your message! We received: "Hello"</Message>
    </Response>
  • Response Body (Error – Invalid Signature): Status 403 Forbidden, Body: Invalid signature
  • Response Body (Error – Missing Headers): Status 400 Bad Request, Body: Missing signature headers

Testing with cURL (Without Valid Signature)

You can simulate a POST request, but without a valid signature, it should be rejected by your validation middleware.

curl -X POST http://localhost:3000/receive_sms \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "From=+15551234567&To=+15557654321&Text=Hello+from+curl&MessageUUID=abc-123"

Proper testing requires sending a real SMS via Plivo or using Plivo's API console/tools that generate correct signatures.


4. Configuring Plivo to Send Webhooks to Your Express App

Connect your Express application to Plivo by configuring a Message URL. During development, use ngrok to expose your local server. Note: The ngrok free tier includes 1 static domain (available since August 2023), keeping your webhook URL consistent. For production, deploy to a server with a stable HTTPS URL.

What Is a Plivo Application?

A Plivo Application tells Plivo where to forward incoming SMS messages. When someone texts your Plivo number, the Application's Message URL determines which webhook endpoint receives the data. Think of it as the routing configuration between your Plivo phone number and your Express server.

  1. Run Your Local Server: Ensure your .env file is populated with your Plivo credentials.
   node server.js

You should see output indicating the server is running on port 3000 (or your configured port).

  1. Expose Local Server with ngrok (Development Only): Open a new terminal window and run ngrok to create a public URL tunnel to your local server's port.
   ngrok http 3000

ngrok displays output similar to this:

   Session Status                online
   Account                       Your Name (Plan: Free)
   Version                       x.x.x
   Region                        United States (us)
   Web Interface                 http://127.0.0.1:4040
   Forwarding                    http://xxxxxxxxxxxx.ngrok.io -> http://localhost:3000
   Forwarding                    https://xxxxxxxxxxxx.ngrok.io -> http://localhost:3000

Copy the https:// forwarding URL (e.g., https://xxxxxxxxxxxx.ngrok.io). This is your temporary public webhook URL for Plivo during development.

  1. Create a Plivo Application:
  • Log in to the Plivo Console.
  • Navigate to Messaging β†’ Applications β†’ XML.
  • Click the "Add New Application" button.
  • Application Name: Give it a descriptive name (e.g., Node Express SMS Handler).
  • Message URL: Paste your https:// ngrok forwarding URL and append your webhook path: https://xxxxxxxxxxxx.ngrok.io/receive\_sms (Replace with your actual ngrok URL or production URL later).
  • Method: Select POST.
  • Hangup URL / Fallback Answer URL: Leave blank for this SMS-only application.
  • Click "Create Application".
  1. Assign the Application to Your Plivo Number:
  • Navigate to Phone Numbers β†’ Your Numbers.
  • Click on the SMS-enabled Plivo number you want to use for receiving messages.
  • In the number configuration screen, find the "Application Type" section. Select XML Application.
  • From the "Plivo Application" dropdown, select the application you just created (Node Express SMS Handler).
  • Click "Update Number".

Your Express application is now linked to your Plivo number. When an SMS is sent to that number, Plivo makes a POST request to your configured URL (ngrok for dev, production URL for live), which forwards it to your server.js application.

Common Configuration Issues

Issue Solution
Webhook URL typo Double-check the URL includes https:// and /receive_sms
Method not POST Verify the Plivo Application uses POST method
Number not assigned Confirm Application is linked to your Plivo number
ngrok not running Ensure ngrok is active and pointing to port 3000

5. Error Handling and Logging

Your current application has basic logging and webhook validation error handling. Enhance the route handler with internal error catching.

  • Consistent Error Strategy: Return specific HTTP statuses (400, 403, 500) for signature errors. For internal processing errors within the /receive\_sms route after validation, wrap your logic in a try...catch block.
  • Logging: console.log provides basic information. For production, use more robust logging libraries like Winston or Pino, which enable structured logging, different log levels (info, warn, error), and routing logs to files or external services.

Enhanced Error Handling

app.post('/receive_sms', validatePlivoSignature, (req, res) => {
    try {
        const from_number = req.body.From;
        const to_number = req.body.To;
        const text = req.body.Text;
        const message_uuid = req.body.MessageUUID;


        if (!from_number || !to_number || !message_uuid) {
             console.warn(`Incomplete message data received: From=${from_number}, To=${to_number}, UUID=${message_uuid}`);

             return res.status(200).send(new plivo.Response().toXML());
        }

        console.log(`Message received on ${to_number} from ${from_number}: "${text || '(empty)'}" (UUID: ${message_uuid})`);


        let reply_text = `Thank you for your message! We received: "${text || '(empty)'}"`;
        if (text && text.toLowerCase().includes('help')) {
            reply_text = `Need help? Contact support@example.com or call 1-800-555-HELP.`;
        } else if (text && text.toLowerCase().includes('stop')) {
            reply_text = `You have been unsubscribed. No more messages will be sent.`;

            console.log(`STOP keyword received from ${from_number}. Unsubscribe logic should run.`);
        }


        const response = new plivo.Response();
        const params = { src: to_number, dst: from_number };
        response.addMessage(reply_text, params);

        const xmlResponse = response.toXML();
        console.log(`Sending XML Response:\n`, xmlResponse);

        res.setHeader('Content-Type', 'application/xml');
        res.status(200).send(xmlResponse);

    } catch (error) {
        console.error(`Error processing incoming SMS ${req.body?.MessageUUID || 'UNKNOWN'}:`, error);



        const errorResponse = new plivo.Response();
        res.setHeader('Content-Type', 'application/xml');


        res.status(200).send(errorResponse.toXML());


    }
});

Plivo Retry Behavior

Plivo automatically retries webhooks three times if it does not receive a 200 OK status code (as of January 2025):

Retry Attempt Timing
First retry 60 seconds after original attempt
Second retry 120 seconds after first retry
Third retry 240 seconds after second retry

By responding 200 OK even in our catch block (with an empty XML response), we tell Plivo we've received the webhook and prevent retries for that specific failure. If the failure is transient and you want Plivo to retry, respond with a 5xx status code. Be cautious, as this could lead to duplicate processing if not handled carefully.

Note: Plivo offers configurable callback retry options (announced May 2024) that let you customize timeout values and retry policies by appending parameters to webhook URLs (e.g., #ct=2000&rt=3000 for connection and read timeouts).


6. Database Schema and Data Layer (Conceptual)

This simple auto-responder doesn't require a database. However, more complex interactions need one:

  • Use Cases: Store conversation history, user profiles, subscription status, order details, etc.
  • Schema Example (Conceptual – e.g., for tracking conversations):
Table Fields
conversations conversation_id (PK), user_phone_number (FK), plivo_number (FK), created_at, last_updated_at, status (e.g., open, closed)
messages message_id (PK), conversation_id (FK), plivo_message_uuid (Unique), direction (inbound/outbound), sender_number, recipient_number, text, timestamp
  • Data Access: Use an ORM like Prisma or Sequelize, or a database driver (e.g., pg for PostgreSQL, mysql2 for MySQL) to interact with the database within your /receive_sms logic. Typically fetch relevant conversation context based on the from_number and to_number before deciding on a reply.
  • Migrations: Use the migration tools provided by your ORM (e.g., prisma migrate dev, sequelize db:migrate) to manage schema changes.

7. Security Features

Security is paramount when exposing webhooks to the internet.

  1. Webhook Signature Validation: Already implemented (validatePlivoSignature). This is the most critical security measure. It ensures requests are authentic and originated from Plivo.
  2. Input Sanitization: While Plivo handles SMS encoding, if you use the Text input in database queries or complex dynamic responses, sanitize it to prevent injection attacks (SQL injection, XSS). Libraries like validator.js can help. For basic replies like this example, the risk is lower.
  3. Rate Limiting: Protect your endpoint from abuse or denial-of-service attacks by limiting the number of requests from a single IP or for a specific Plivo number. Use middleware like express-rate-limit.
   npm install express-rate-limit
   const rateLimit = require('express-rate-limit');

   const limiter = rateLimit({
       windowMs: 15 * 60 * 1000,
       max: 100,
       message: 'Too many requests, please try again later.',
       standardHeaders: true,
       legacyHeaders: false,
   });

   app.use('/receive_sms', limiter);
  1. HTTPS: Always use HTTPS for your webhook URL in production. ngrok provides this automatically for development. In production, ensure your server is configured behind a reverse proxy (like Nginx or Apache) or load balancer that handles SSL/TLS termination, or use a PaaS that provides it. Plivo requires HTTPS for production webhooks.
  2. Environment Variables: Keep sensitive information (Plivo Auth Token, database credentials) out of your code and use environment variables (.env locally, system environment variables in production). Ensure .env is in .gitignore.
  3. Common Vulnerabilities: Be aware of OWASP Top 10 vulnerabilities and how they might apply, especially if you add database interactions or more complex logic.

Security Checklist

  • Webhook signature validation enabled
  • Rate limiting configured
  • HTTPS enforced in production
  • Environment variables secured
  • Input sanitization for database queries
  • .env file in .gitignore
  • Error messages don't expose sensitive data

8. Handling Special Cases

  • Message Encoding: Plivo handles standard SMS encodings (GSM-7, UCS-2). The Text field in the webhook payload contains the decoded message content. Be aware of character limits (160 for GSM-7, 70 for UCS-2 per segment).
  • Concatenated Messages (Long SMS): Longer messages are split into multiple segments by carriers. Plivo usually forwards these as separate webhook requests. To reassemble them, look for parameters like ParentMessageUUID (identifies the original message) and potentially sequence number parameters in the webhook payload. Buffer these parts (e.g., in memory, cache, or database) until all segments arrive before processing the full message. Consult the Plivo documentation for the exact parameters and recommended handling logic for message concatenation.
  • Time Zones: Timestamps from Plivo are in UTC. Store timestamps in your database in UTC and convert to the user's local time zone for display if necessary.
  • "STOP" / Opt-Out: Plivo handles standard opt-out keywords (STOP, UNSUBSCRIBE, etc.) at the carrier level for Toll-Free and Short Code numbers if enabled in your Plivo number's configuration. However, you must also implement logic in your application to honor these requests (e.g., flagging the user as unsubscribed in your database) to comply with regulations (like TCPA in the US). Our example includes a basic keyword check but requires adding the actual database/system update logic.
  • Rate Limits / Throttling: Plivo enforces rate limits on sending messages. Your application might also be throttled by Plivo if it responds too slowly or incorrectly too often. Ensure your webhook responds quickly (ideally under 1–2 seconds; Plivo timeout is 5 seconds).
  • Duplicate Messages: Network issues can occasionally cause Plivo to send duplicate webhooks (especially if your server doesn't respond promptly). Use the MessageUUID to deduplicate messages by checking if you've already processed that UUID in your database or a cache (like Redis) within a short time window before processing.

Character Encoding Limits

Encoding Characters per Segment Use Case
GSM-7 160 Standard English text
UCS-2 70 Emoji, special characters, non-Latin scripts

9. Performance Optimizations

For this simple application, performance is less critical, but consider these for scaling:

  • Fast Webhook Response: The most crucial optimization. Do minimal work synchronously within the webhook handler. If extensive processing is needed (calling external APIs, complex database queries), acknowledge the webhook quickly (send the XML response) and perform the heavy lifting asynchronously using a job queue (e.g., BullMQ, Kue with Redis) or background process.
  • Caching: Cache frequently accessed data (e.g., user profiles, common replies) using Redis or Memcached to reduce database load.
  • Efficient Database Queries: Index database columns used in lookups (e.g., user_phone_number, plivo_message_uuid).
  • Load Testing: Use tools like k6, Artillery, or ApacheBench (ab) to simulate high traffic to your webhook endpoint and identify bottlenecks.
  • Node.js Clustering: Use Node.js's built-in cluster module or a process manager like PM2 in cluster mode to run multiple instances of your application across CPU cores, improving throughput.

Performance Targets

Metric Target Critical Threshold
Webhook response time < 1 second < 2 seconds
Success rate > 99.5% > 99%
Concurrent requests 100+ req/sec 50+ req/sec

10. Monitoring, Observability, and Analytics

  • Health Checks: The /health endpoint provides a basic check. Monitoring services (like UptimeRobot, Pingdom, AWS CloudWatch) can ping this endpoint to ensure your application is running.
  • Performance Metrics (APM): Use Application Performance Monitoring tools (e.g., Datadog, New Relic, Dynatrace, Sentry APM) to track response times, error rates, resource usage (CPU, memory), and Node.js-specific metrics (event loop lag). These tools often auto-instrument Express applications.
  • Error Tracking: Integrate services like Sentry or Bugsnag to capture, aggregate, and alert on application errors (going beyond basic console logging).
  • Logging Aggregation: Ship logs (using Winston/Pino transports) to a centralized logging platform (e.g., ELK stack, Datadog Logs, Logz.io, Sematext) for easier searching, analysis, and alerting based on log patterns.
  • Key Metrics Dashboard: Create dashboards (in your APM, logging tool, or Grafana) showing:
  • Incoming message rate
  • Webhook response time (average, p95, p99)
  • Webhook error rate (4xx, 5xx)
  • Signature validation failures
  • Message processing latency (if using async processing)
  • Alerting: Configure alerts based on thresholds (e.g., error rate > 1%, response time > 2 seconds, health check fails).

Essential Metrics to Track

Category Metrics
Performance Response time (avg, p95, p99), throughput (messages/min)
Reliability Success rate, error rate, uptime percentage
Security Signature validation failures, rate limit hits
Business Messages received, unique users, keyword usage

11. Troubleshooting and Caveats

ngrok Issues (Development)

  • Ensure ngrok is running and pointing to the correct local port (3000 in this example).
  • Free tier users: As of August 2023, the free tier includes 1 static domain that persists across sessions. If using a random domain (non-static), the URL expires and requires updating in Plivo.
  • Firewalls might block ngrok traffic.

Plivo Configuration Errors

  • Incorrect Message URL: Double-check for typos, correct protocol (HTTPS required for production), and ensure the /receive\_sms path is included.
  • Incorrect Method: Ensure the method is set to POST in the Plivo Application.
  • Number Not Assigned: Verify the Plivo Application is correctly assigned to the intended Plivo phone number.
  • Number Not SMS Enabled: Ensure the Plivo number is capable of sending/receiving SMS in the relevant region.

Webhook Signature Validation Failures

  • Incorrect Auth Token: Verify the PLIVO\_AUTH\_TOKEN in your .env file or production environment variables exactly matches the one in the Plivo console.
  • URL Mismatch: Ensure the URL constructed in the validation logic matches precisely how Plivo calls your webhook (check ngrok logs, Plivo debug logs, or your server access logs). Proxies can sometimes alter URLs/host headers.
  • Implementation Error: Double-check the usage of plivo.validateV3Signature.

Code Errors

  • Check server logs (node server.js output or aggregated logs) for runtime errors.
  • Ensure all dependencies are installed (npm install).
  • Verify XML generation logic (response.addMessage, response.toXML()). Invalid XML causes Plivo replies to fail silently or with errors in Plivo logs.

Other Common Issues

  • Plivo Trial Account Limitations: You can only send messages to and receive messages from numbers verified in your Plivo Sandbox (Phone Numbers > Sandbox Numbers).
  • Plivo Platform Status: Check the Plivo Status Page if you suspect a platform-wide issue.
  • Delayed Messages/Replies: SMS is not guaranteed real-time. Delays can occur due to carrier network congestion.
  • Firewall Blocking Plivo: Ensure your production server's firewall allows incoming connections from Plivo's IP addresses on the relevant port (usually 443 for HTTPS). Consult Plivo's documentation or support for the specific IP ranges if needed for firewall configuration.

12. Deployment and CI/CD

Deploy your Node.js/Express application to a server and ensure it restarts automatically. Replace your temporary ngrok URL in Plivo with your permanent production HTTPS URL.

Choose a Hosting Platform

Platform Type Examples Best For
PaaS Heroku, Render, Fly.io Simple deployment, managed HTTPS
IaaS AWS EC2, Google Compute Engine, DigitalOcean Full control, custom configuration
Serverless AWS Lambda + API Gateway Low/variable traffic, cost efficiency

Prepare for Production

  • Environment Variables: Configure PLIVO\_AUTH\_ID, PLIVO\_AUTH\_TOKEN, and PORT on the production server (do not commit .env). Platforms like Heroku have config vars; servers use system environment variables.
  • Use a Process Manager: Use PM2 to manage your Node.js process, handle restarts on failure, enable clustering, and manage logs.

Basic PM2 Commands

npm install -g pm2

pm2 start server.js --name "plivo-sms-app"

pm2 startup
pm2 save

pm2 monit

pm2 logs

13. Testing Strategies


14. Compliance and Legal Considerations


15. Real-World Examples and Use Cases


Conclusion

You now know how to receive SMS messages in Node.js using Plivo and Express. You've built a production-ready webhook handler with:

  • A secure endpoint that validates Plivo signatures
  • Automated SMS reply functionality based on keywords
  • Error handling and logging for reliability
  • Configuration for local development and production deployment

Next Steps

  1. Add database integration – Store conversation history and user preferences
  2. Implement advanced logic – Build conversation flows and state management
  3. Deploy to production – Choose a hosting platform and configure CI/CD
  4. Monitor and optimize – Set up APM tools and track key metrics
  5. Ensure compliance – Review TCPA and GDPR requirements for your use case
  • Plivo SMS API Documentation
  • Plivo Node.js SDK Reference
  • Express.js Official Documentation
  • Plivo Status Page
  • SMS Compliance Guidelines (TCPA)

Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)

If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.

curl -X POST https://api.sendsmsnokyc.com/messages \
  -H "x-api-key: $SMSROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["+14155551234"],
    "channel": ["sms"],
    "body": "Your verification code is 482910"
  }'
  • Instant onboarding: No KYC paperwork or sales queues β€” grab an API key and fund with crypto (BTC/USDT) or card.
  • Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
  • Transparent global pricing: Compare exact per-country termination rates on our live pricing page.

Ship Global SMS in One API Call

Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.

Explore SMSRoute Developers β†’