Frequently Asked Questions
Use Node.js with Express.js and the Plivo Node.js SDK to build an application that interacts with the Plivo API for sending SMS messages. The application can accept campaign details, send messages, handle replies, and store campaign data. This guide provides a walkthrough for setting up this system.
Plivo is a cloud communication platform that provides the necessary infrastructure for sending SMS messages, managing phone numbers, and receiving webhooks for incoming replies and delivery reports. It acts as the SMS gateway for the Node.js application.
Node.js is chosen for its asynchronous, event-driven architecture. This makes it highly efficient for I/O-heavy tasks like handling API interactions and webhook requests, which are central to sending and managing SMS campaigns effectively.
Express.js simplifies the creation of the web server and API endpoints needed for managing campaign requests and Plivo webhooks. It provides a minimal and flexible framework for handling HTTP requests and responses.
Use npm (or yarn) to install the required packages: npm install express plivo dotenv body-parser. For development, install nodemon with: npm install --save-dev nodemon to automatically restart the server on code changes.
ngrok creates a public tunnel to your locally running development server. This allows Plivo's webhooks to reach your application during development, as Plivo needs a publicly accessible URL to send webhook requests to.
Create a .env file in the project root and store your Plivo Auth ID, Auth Token, Plivo phone number, server port, and ngrok URL (during development) in this file. This is crucial for security best practices.
Configure a Plivo application with a webhook URL pointing to your /webhooks/inbound-sms endpoint. When a user replies to a campaign message, Plivo will send a request to this URL. You can then process the reply within your application.
In your Plivo Application settings, configure a Delivery Report URL pointing to an endpoint in your app, such as /webhooks/status, and select the POST method. Plivo will then send delivery status updates (e.g., sent, delivered, failed) to this URL.
While the tutorial provides a simplified example, for production systems, avoid sending many messages in a tight loop. Implement rate limiting, such as sending one message per second, or use a message queue like RabbitMQ or Redis Queue for better performance and reliability.
Your Plivo Auth ID and Auth Token can be found on your Plivo Console dashboard under "API -> Keys & Tokens". These credentials are necessary to authenticate with the Plivo API.
Trial Plivo accounts have limitations. You can send test messages to verified numbers within your Plivo Sandbox. Ensure the recipient numbers you use for testing are added and verified in your sandbox environment.
The tutorial uses an in-memory store for simplicity, but this isn't suitable for production. Integrate a database (e.g., PostgreSQL, MySQL, MongoDB) to persist campaign details, recipient information, and message statuses reliably.
Robust input validation prevents unexpected errors and potential security issues. The tutorial demonstrates basic checks, but use libraries like express-validator to thoroughly sanitize and validate user-provided data in a production environment.
Complete Guide: Sending Bulk SMS Marketing Campaigns with Plivo (Node.js, Express)
Learn how to build a production-ready SMS marketing campaign system using Plivo's SMS API, Next.js 15, Supabase, and Node.js. This comprehensive guide covers everything from initial setup through deployment, including bulk SMS sending, TCPA compliance, webhook handling, and subscriber management.
Note: This guide adapts the Express-based implementation for Next.js API routes with Supabase for authentication and data persistence. The core Plivo integration patterns remain consistent across frameworks.
By completing this tutorial, you'll have a fully functional SMS marketing automation platform that sends targeted campaigns, processes delivery reports, manages subscriber opt-outs, and scales for production workloads.
What You'll Build: SMS Marketing Platform Overview
Application Features:
A Next.js application with Supabase backend that executes SMS marketing campaigns via Plivo's API.
Core System Capabilities:
Real-World Problem This Solves:
Manual SMS marketing doesn't scale beyond small lists. This automated system handles bulk messaging, tracks engagement metrics, processes opt-outs instantly, and maintains compliance—all while integrating seamlessly with your existing Next.js application.
TCPA Compliance Is Critical:
SMS marketing is heavily regulated in the United States. Your application must comply with:
Technology Stack:
System Architecture Flow:
Your system operates as follows:
Prerequisites for Building Your SMS Marketing System
Before starting development, ensure you have:
ngrokinstalled for local webhook testing (Download ngrok)Plivo Trial Account Limitations:
Step 1: Initialize Your Next.js SMS Marketing Project
Set up your Next.js project with required dependencies and configuration.
Create Next.js Project: Initialize a new Next.js application with TypeScript and App Router.
When prompted, select:
src/directory: YesInstall Required Dependencies: Install Plivo SDK, Supabase client, form handling, and validation libraries.
Why these dependencies:
plivo: Official Plivo Node.js SDK for SMS operations@supabase/supabase-js&@supabase/ssr: Supabase client libraries for Next.js@tanstack/react-query: Powerful data fetching and cachingreact-hook-form+zod: Type-safe form handling and validationdate-fns: Date/time manipulation for schedulingclsx: Utility for constructing className stringsSet Up Environment Variables: Create
.env.localfile in project root. This stores sensitive credentials. Never commit to version control.Where to find credentials:
openssl rand -base64 32Configure Supabase Client: Create utility files for Supabase client initialization.
Browser client (
src/lib/supabase/client.ts):Server client (
src/lib/supabase/server.ts):Service role client for admin operations (
src/lib/supabase/admin.ts):> Why multiple clients: Browser client for frontend, server client for API routes with cookie handling, admin client for privileged operations like bulk operations.
Initialize Plivo Client: Create a configuration file for Plivo SDK initialization.
> Why: Centralizing Plivo client initialization ensures consistent configuration and validates required environment variables at startup.
Configure TypeScript: Update
tsconfig.jsonfor better path aliases and strict typing.Create Project Structure: Organize directories for maintainability and scalability.
Update
.gitignore: Ensure sensitive files never get committed.You now have a solid foundation with Next.js, Supabase, and Plivo configured and ready for development.
Step 2: Set Up Supabase Database Schema
Create database tables for subscribers, campaigns, and message tracking.
Access Supabase SQL Editor:
Create Database Tables: Execute this SQL to create your schema with proper indexes and constraints.
Schema design rationale:
updated_attimestampsCreate TypeScript Types: Generate type definitions matching your database schema.
Your database schema is now configured with proper relationships, indexes, and security policies.
Step 3: Build Subscriber Management API
Create Next.js API routes for managing subscriber data with CRUD operations.
Create Validation Schema: Define Zod schemas for type-safe validation.
Create Subscriber API Routes: Implement CRUD endpoints with proper error handling.
Individual subscriber operations (
src/app/api/subscribers/[id]/route.ts):> Why: These API routes provide complete subscriber management with validation, error handling, and proper HTTP status codes. Phone number uniqueness is enforced at the database level.
Test Subscriber API: Use curl or Postman to verify endpoints.
Your subscriber management API is now fully functional with validation and error handling.
Step 4: Build Campaign Management API
Create endpoints for managing SMS marketing campaigns.
Create Campaign Validation: Define schemas for campaign creation and updates.
Create Campaign API Routes: Implement campaign CRUD operations.
Individual campaign operations (
src/app/api/campaigns/[id]/route.ts):Create Campaign Send Endpoint: Build API route to trigger campaign sending.
> Production Note: This synchronous approach works for small lists but doesn't scale. Section 5 covers implementing a background job queue for production-grade bulk sending.
Your campaign management system is now operational with sending capabilities.
Step 5: Implement Plivo Webhooks for Delivery Reports
Set up webhook endpoints to receive and process Plivo callbacks.
Configure ngrok for Local Testing: Expose your local development server to receive webhooks.
Copy the HTTPS forwarding URL (e.g.,
https://abc123.ngrok.io).Update Environment Variable: Set your ngrok URL in
.env.local:Restart your dev server after changing environment variables.
Configure Plivo Webhook URL:
https://abc123.ngrok.io/api/webhooks/incominghttps://abc123.ngrok.io/api/webhooks/statusCreate Webhook Signature Validation: Implement security verification for incoming webhooks.
Create Delivery Status Webhook: Process delivery reports from Plivo.
Create Incoming SMS Webhook: Handle replies and process opt-out keywords.
> Why Plivo XML: Plivo expects XML responses for immediate replies. The
plivo.Response()object generates proper XML for auto-reply functionality.Test Webhooks: Send test messages to verify webhook processing.
Your webhook system now processes delivery reports and handles opt-outs automatically.
Frequently Asked Questions About Plivo SMS Marketing
How do I get started with Plivo SMS marketing in Next.js?
Start by creating a Plivo account, purchasing an SMS-enabled phone number ($0.80–$2.00/month), and setting up a Next.js 15 project with Supabase. Install the Plivo Node.js SDK v4 with
npm install plivo, configure environment variables with your Auth ID and Auth Token, and create API routes for sending messages. This guide provides complete code examples for production implementation.What is TCPA compliance and why does it matter for SMS marketing?
TCPA (Telephone Consumer Protection Act) compliance is legally required when sending marketing SMS to US phone numbers. Key requirements include: obtaining express written consent before sending messages, providing clear opt-out instructions ("Reply STOP to unsubscribe"), honoring opt-outs immediately, and maintaining consent records. Violations carry penalties up to $1,500 per message. Similar regulations exist globally (GDPR in EU, CASL in Canada).
How much does Plivo SMS cost for marketing campaigns?
Plivo charges approximately $0.0035–$0.0075 per SMS segment for US/Canada destinations. International rates vary by country ($0.005–$0.20 per segment). Phone numbers cost $0.80–$2.00/month. A 160-character message equals 1 segment; longer messages use multiple segments. Trial accounts include 20 free messages but have restrictions (verified numbers only, "[Plivo Trial]" prefix). Check Plivo's pricing page for current rates.
Can I use Next.js instead of Express for Plivo integration?
Yes, Plivo works seamlessly with Next.js API routes. Replace Express endpoints with Next.js route handlers in the
app/apidirectory. The Plivo SDK code remains identical—only the framework wrapper changes. This guide demonstrates complete Next.js implementation with App Router, server components, and API routes.How do I handle SMS opt-outs with Plivo webhooks?
Configure an incoming message webhook in your Plivo application settings. Create a Next.js API route (
/api/webhooks/incoming) that receives POST requests from Plivo. Parse the message text for opt-out keywords (STOP, UNSUBSCRIBE, CANCEL, END, QUIT), update the subscriber'sis_activestatus in Supabase, and send a confirmation message. Process opt-outs in real-time to maintain TCPA compliance.What is Supabase and why use it for SMS campaigns?
Supabase is an open-source Backend-as-a-Service providing PostgreSQL database, authentication, real-time subscriptions, and RESTful API. Use Supabase for SMS campaigns to get: managed PostgreSQL with automatic backups, Row Level Security for data protection, real-time updates for campaign dashboards, and built-in authentication. It eliminates backend infrastructure setup and scales automatically.
How do Plivo webhooks work for delivery status?
Plivo sends HTTP POST requests to your configured endpoint when message status changes. Configure the webhook URL in Plivo Console > Messaging > Applications > Delivery Report URL. Your API route receives delivery status (queued, sent, delivered, undelivered, failed), message UUID, timestamp, and error codes. Always validate webhook signatures to prevent unauthorized requests.
What's the difference between synchronous and queue-based SMS sending?
Synchronous sending processes messages sequentially within the API request, limiting scalability to small lists. Queue-based sending (using BullMQ or Vercel Queue) offloads message processing to background workers, allowing API routes to return immediately. Use queues for production to handle bulk campaigns, implement retry logic, enforce rate limits, and scale horizontally.
How do I validate phone numbers for Plivo SMS?
Use E.164 format validation:
+followed by country code and subscriber number (1-15 digits). Basic regex:/^\+[1-9]\d{1,14}$/. For production, uselibphonenumber-jsfor comprehensive validation including country-specific rules. Implement validation in Zod schemas before database insertion. This prevents invalid numbers and reduces Plivo API errors.Can I schedule SMS campaigns for specific times?
Yes, store the desired send time in the campaign's
scheduled_atfield. Implement a scheduled job using Vercel Cron Jobs (for Vercel deployments) or Next.js middleware that checks for pending campaigns. Query campaigns wherescheduled_at <= now()andstatus = 'scheduled', then trigger the send process. For complex scheduling, integrate a job queue like BullMQ with delayed jobs.How do I test Plivo webhooks during local development?
Use ngrok to expose your local Next.js server to the internet. Run
ngrok http 3000, copy the HTTPS URL (e.g.,https://abc123.ngrok.io), and configure it as your webhook URL in Plivo Console. UpdateNEXT_PUBLIC_APP_URLin.env.localto the ngrok URL. Ngrok tunnels incoming webhook requests to your local server, enabling real-time testing.What database schema do I need for SMS marketing campaigns?
Create three core tables:
subscribers(phone numbers, consent, opt-out status),campaigns(name, message body, status, statistics), andsent_messages(delivery tracking with Plivo message UUIDs). Add indexes on phone numbers, campaign status, and message UUIDs for query performance. Use foreign keys with CASCADE deletes for referential integrity. Enable Supabase Row Level Security for data protection.Conclusion: Your Production-Ready SMS Marketing Platform
You've built a complete SMS marketing campaign system using Plivo, Next.js 15, and Supabase. Your application now includes:
Core Features Implemented:
Next Steps for Production:
Production Deployment Checklist:
next-rate-limitSecurity Best Practices:
.env.localto version controlThis foundation provides everything needed for a scalable SMS marketing platform. Customize these components to match your specific business requirements while maintaining code quality, security, and compliance standards.
For questions about Plivo integration, consult the Plivo Node.js SDK documentation and Next.js API routes guide.