Developer Quick-Start: Step-by-step tutorial: Integrate Plivo's WhatsApp Business API into Next.js. Send/receive messages, handle webhooks, and build production-ready WhatsApp messaging in your Node.js app. 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.
This comprehensive guide walks you through integrating Plivo's WhatsApp Business API into your Next.js application. You'll learn how to build a production-ready solution for sending and receiving WhatsApp messages, handling webhooks securely, and managing message templates effectively.
We'll cover everything from initial project setup to webhook configuration, enabling you to leverage WhatsApp for customer communication, notifications, or interactive services directly within your Next.js app. By the end, you'll have a functional WhatsApp messaging application ready for production use cases.
Project Overview and Goals
What We're Building:
A Next.js application with API routes that can:
- Send WhatsApp Messages: Trigger outgoing messages (text, media, templates, interactive) via Plivo's API through a secure backend endpoint.
- Receive WhatsApp Messages: Handle incoming messages and status updates from Plivo via a secure webhook endpoint.
Problem Solved:
This integration enables direct, programmatic communication with users on WhatsApp, bypassing the need for manual messaging or less integrated solutions. It's ideal for applications requiring timely notifications, customer support interactions, or automated conversational flows over WhatsApp.
Technologies Used:
- Next.js: A React framework providing server-side rendering, API routes, and a streamlined developer experience (v15.x as of 2025, with App Router requiring React 19). Chosen for its integrated backend capabilities (API routes) and popularity in modern web development.
- Node.js: The underlying runtime for Next.js and the Plivo SDK.
- Plivo Node.js SDK: Simplifies interaction with the Plivo REST API for sending messages and handling communication logic.
- Plivo WhatsApp Business API: The service providing the connection to the WhatsApp network.
- (Optional)
ngrok: For exposing local development servers to the internet to test webhooks.
System Architecture:
graph LR
A[User/Client App] -- HTTP Request --> B(Next.js Frontend);
B -- API Call --> C{Next.js API Route (/api/send-whatsapp)};
C -- Plivo SDK --> D[Plivo API];
D -- WhatsApp Network --> E[End User WhatsApp];
E -- Sends Message --> D;
D -- Webhook POST --> F{Next.js API Route (/api/plivo-webhook)};
F -- Process/Log --> G[(Optional) Database/Logging Service];
F -- 200 OK --> D;
style C fill:#f9f,stroke:#333,stroke-width:2px
style F fill:#f9f,stroke:#333,stroke-width:2px
Prerequisites:
- Node.js (v20 "Iron" or v22 "Jod" recommended β current LTS versions as of 2025. Production applications should use Active LTS or Maintenance LTS releases)
- npm or yarn package manager
- A Plivo account with Auth ID and Auth Token.
- A WhatsApp Business Account (WABA) and a Plivo-approved WhatsApp Sender number configured in your Plivo console.
- Basic understanding of Next.js, APIs, and JavaScript.
- (Optional) ngrok installed for local webhook testing.
Final Outcome:
A Next.js application with two API endpoints: one to trigger outgoing WhatsApp messages and another to receive incoming messages/statuses from Plivo. The setup will use environment variables for security and include basic error handling.
1. Setting Up Your Next.js WhatsApp Project
Let's initialize a new Next.js project and install the necessary dependencies for WhatsApp messaging.
- Create a Next.js App: Open your terminal and run the following command. Choose your
preferred settings when prompted (we'll use TypeScript: No, ESLint: Yes, Tailwind CSS: No,
src/directory: No, App Router: Yes, customize import alias: No for this guide).
npx create-next-app@latest plivo-nextjs-whatsapp
- Navigate to Project Directory:
cd plivo-nextjs-whatsapp
- Install Plivo Node.js SDK: Add the Plivo SDK to your project dependencies.
npm install plivo
- Set Up Environment Variables: Create a file named
.env.localin the root of your project. This file is gitignored by default in Next.js and is the secure place for your credentials. Add your Plivo Auth ID and Auth Token.
- Find your Auth ID and Auth Token on the Plivo Console dashboard homepage.
# .env.local
# Plivo Credentials
PLIVO_AUTH_ID=YOUR_PLIVO_AUTH_ID
PLIVO_AUTH_TOKEN=YOUR_PLIVO_AUTH_TOKEN
# Your Plivo WhatsApp Sender Number (in E.164 format, e.g., +14155552671)
PLIVO_WHATSAPP_SENDER_NUMBER=+1XXXXXXXXXX
# Optional: A secret token if implementing additional custom webhook checks
# PLIVO_WEBHOOK_SECRET=your_strong_random_secret_here
PLIVO_AUTH_ID/PLIVO_AUTH_TOKEN: Used by the SDK to authenticate API requests to Plivo. Obtainable from the Plivo Console dashboard. This is also used for validating incoming webhooks.PLIVO_WHATSAPP_SENDER_NUMBER: Your Plivo-provisioned WhatsApp number used as the src for outgoing messages. Find this under Messaging -> WhatsApp Senders in the Plivo Console.PLIVO_WEBHOOK_SECRET: (Commented out by default) A secret you define. Plivo doesn't use this directly for its standard signature validation. You might use it if implementing additional custom verification logic beyond Plivo's signature check. Note: Plivo's primary webhook security relies on signature validation using yourPLIVO_AUTH_TOKEN, which is covered later.
- Project Structure: Your basic structure (using App Router) will look something like this:
plivo-nextjs-whatsapp/
βββ app/
β βββ api/ # API routes live here
β β βββ send-whatsapp/
β β β βββ route.js
β β βββ plivo-webhook/
β β βββ route.js
β βββ layout.js
β βββ page.js
βββ node_modules/
βββ public/
βββ .env.local # Your secret credentials
βββ .gitignore
βββ next.config.mjs
βββ package.json
βββ README.md
We place our backend logic within the app/api/ directory, following Next.js conventions for API
routes.
2. Building the WhatsApp Messaging API Endpoint
We'll create an API route that accepts a request (containing destination number and message content) and uses the Plivo SDK to send a WhatsApp message.
- Create the Send API Route: Create the file
app/api/send-whatsapp/route.js. - Implement the Sending Logic: Add the following code to
app/api/send-whatsapp/route.js.
import { NextResponse } from 'next/server';
import plivo from 'plivo';
const authId = process.env.PLIVO_AUTH_ID;
const authToken = process.env.PLIVO_AUTH_TOKEN;
const plivoWhatsappNumber = process.env.PLIVO_WHATSAPP_SENDER_NUMBER;
if (!authId || !authToken || !plivoWhatsappNumber) {
console.error("Missing Plivo credentials or sender number in environment variables.");
}
let client;
try {
if (authId && authToken) {
client = new plivo.Client(authId, authToken);
} else {
throw new Error("Plivo client cannot be initialized due to missing credentials.");
}
} catch (error) {
console.error("Failed to initialize Plivo client:", error);
}
export async function POST(request) {
if (!client) {
console.error("Plivo client is not initialized. Check server logs for initialization errors.");
return NextResponse.json(
{ success: false, error: "Server configuration error: Plivo client not available." },
{ status: 500 }
);
}
let requestBody;
try {
requestBody = await request.json();
} catch (error) {
return NextResponse.json({ success: false, error: "Invalid JSON body" }, { status: 400 });
}
const { to, message, type = 'text',
media_urls, template, interactive, location } = requestBody;
if (!to || !to.startsWith('+') || to.length < 10) {
return NextResponse.json({ success: false, error: "Invalid 'to' phone number format. Use E.164 (e.g., +14155552671)." }, { status: 400 });
}
if (type === 'text' && !message) {
return NextResponse.json({ success: false, error: "Missing 'message' field for text message." }, { status: 400 });
}
if (type === 'media' && (!media_urls || !Array.isArray(media_urls) || media_urls.length === 0)) {
return NextResponse.json({ success: false, error: "Missing or invalid 'media_urls' array for media message." }, { status: 400 });
}
if (type === 'template' && !template) {
return NextResponse.json({ success: false, error: "Missing 'template' object for template message." }, { status: 400 });
}
if (type === 'interactive' && !interactive) {
return NextResponse.json({ success: false, error: "Missing 'interactive' object for interactive message." }, { status: 400 });
}
if (type === 'location' && !location) {
return NextResponse.json({ success: false, error: "Missing 'location' object for location message." }, { status: 400 });
}
const payload = {
src: plivoWhatsappNumber,
dst: to,
type: 'whatsapp',
};
switch(type) {
case 'text':
payload.text = message;
break;
case 'media':
payload.media_urls = media_urls;
if (message) payload.text = message;
break;
case 'template':
payload.template = template;
break;
case 'interactive':
payload.interactive = interactive;
break;
case 'location':
payload.location = location;
break;
default:
return NextResponse.json({ success: false, error: `Unsupported message type: ${type}` }, { status: 400 });
}
try {
const response = await client.messages.create(payload);
console.log("Plivo API Response:", response);
return NextResponse.json({
success: true,
message_uuid: response.messageUuid?.[0],
api_id: response.apiId,
message: response.message,
});
} catch (error) {
console.error("Plivo API Error:", error);
const errorMessage = error.message || "Failed to send message via Plivo.";
const errorStatus = error.statusCode || 500;
return NextResponse.json(
{ success: false, error: errorMessage, details: error.error },
{ status: errorStatus }
);
}
}
Explanation:
- We import NextResponse for API responses and the plivo SDK.
- We retrieve Plivo credentials and the sender number from environment variables. Crucially, we check if they exist before initializing the client. An error is thrown if initialization fails due to missing credentials.
- The Plivo client is initialized using the Auth ID and Token. This happens outside the POST handler for potential reuse.
- The POST function handles incoming requests. It first checks if the client was successfully initialized. It expects a JSON body containing to (destination number) and fields specific to the message type (e.g., message for text, media\_urls for media, template object, interactive object, location object).
- Basic input validation is performed on the to number and required fields based on type.
- We construct the payload object for the client.messages.create method, setting src, dst, and type: 'whatsapp'.
- A switch statement adds the correct parameters (text, media\_urls, template, etc.) based on the requested type.
- The client.messages.create(payload) function sends the request to Plivo.
- We wrap the API call in a try...catch block to handle potential errors from the Plivo API (e.g., invalid number, insufficient funds, API downtime).
- On success, we return the Plivo message UUID and API ID.
- On error, we log the error and return a JSON response with the error message and appropriate status code (using Plivo's status code if available).
3. Implementing WhatsApp Webhook Handler for Incoming Messages
Plivo uses webhooks to send your application information about incoming messages or status updates for outgoing messages. We need an API route to receive these webhook POST requests.
- Create the Webhook API Route: Create the file
app/api/plivo-webhook/route.js. - Implement the Webhook Handler: Add the following code to
app/api/plivo-webhook/route.js.
import { NextResponse } from 'next/server';
import plivo from 'plivo';
import { headers } from 'next/headers';
const authToken = process.env.PLIVO_AUTH_TOKEN;
function validatePlivoSignature(request, rawBody) {
const headerList = headers();
const signature = headerList.get('X-Plivo-Signature-V3');
const nonce = headerList.get('X-Plivo-Signature-V3-Nonce');
const url = request.url;
if (!signature || !nonce || !authToken) {
console.warn("Webhook validation skipped: Missing 'X-Plivo-Signature-V3' header, 'X-Plivo-Signature-V3-Nonce' header, or 'PLIVO_AUTH_TOKEN'.");
return false;
}
try {
console.error("CRITICAL SECURITY WARNING: Plivo signature validation logic is NOT IMPLEMENTED. Using placeholder. Replace with logic from Plivo documentation IMMEDIATELY.");
return false;
} catch (error) {
console.error("Error during (placeholder) signature validation:", error);
return false;
}
}
export async function POST(request) {
let rawBody;
try {
rawBody = await request.text();
console.warn("Plivo signature validation is currently bypassed or using placeholder logic. IMPLEMENT PROPER VALIDATION!");
const data = JSON.parse(rawBody);
console.log("Received Plivo Webhook Data:", JSON.stringify(data, null, 2));
const messageType = data.Type;
const fromNumber = data.From;
const toNumber = data.To;
const messageUuid = data.MessageUUID;
if (messageType === 'message') {
const text = data.Text;
const mediaUrl = data.MediaUrl;
const mediaContentType = data.MediaContentType;
const buttonPayload = data.Button?.Payload;
const listId = data.List?.Id;
console.log(`Incoming message from ${fromNumber}: ${text || ('Media: ' + mediaUrl) || 'Interactive Response (check payload/ID)'}`);
if (buttonPayload) {
console.log(`Button Payload: ${buttonPayload}`);
}
if (listId) {
console.log(`List Selection ID: ${listId}`);
}
} else if (messageType === 'message_status') {
const status = data.MessageStatus;
console.log(`Status update for message ${messageUuid}: ${status}`);
if (status === 'failed' || status === 'undelivered') {
const errorCode = data.ErrorCode;
console.error(`Message ${messageUuid} failed with code: ${errorCode}. Error details: ${data.ErrorReason || 'N/A'}`);
}
} else {
console.log(`Received unhandled webhook type: ${messageType}`);
}
return new Response(null, { status: 200 });
} catch (error) {
if (error instanceof SyntaxError && rawBody !== undefined) {
console.error("Failed to parse webhook JSON body:", error);
return NextResponse.json({ success: false, error: "Invalid JSON received" }, { status: 400 });
} else {
console.error("Error processing Plivo webhook:", error);
return NextResponse.json({ success: false, error: "Internal server error processing webhook" }, { status: 500 });
}
}
}
Explanation:
- Signature Validation Function (
validatePlivoSignature): - This is the most critical security component for your webhook. It verifies that incoming requests originate from Plivo.
- Placeholder Warning: The provided function is a placeholder only. It demonstrates the concept but lacks the actual validation logic.
- Action Required: You must consult the official Plivo documentation for Node.js and replace the placeholder section with Plivo's recommended signature validation method. This might involve using a utility function from the Plivo Node.js SDK (if available) or manually implementing the HMAC-SHA256 validation steps using the request URL, nonce header (X-Plivo-Signature-V3-Nonce), signature header (X-Plivo-Signature-V3), your Plivo Auth Token, and the raw request body.
- Do not deploy to production without implementing and testing correct signature validation. The current code defaults to failing validation (return false;) for safety if the placeholder isn't replaced.
- Webhook Handler (
POST): - Reads the raw request body using request.text() before JSON parsing, as the raw body is essential for signature validation.
- Validation Call (Commented Out): The call to validatePlivoSignature is commented out initially. You must uncomment and integrate it once the validation function is correctly implemented. If validation fails, a 403 Forbidden response should be returned.
- Parsing: After successful validation (or during testing with the bypass), the raw body is parsed into a JSON object using JSON.parse().
- Processing: The code logs the incoming data, checks the Type field (message or message\_status), and extracts relevant information. It includes examples for handling text, media, and basic interactive message responses (button clicks, list selections).
- Business Logic: Placeholder comments indicate where your application-specific logic (database interaction, automated replies, etc.) should be added.
- Acknowledgement: A 200 OK response with an empty body is returned to Plivo upon successful receipt and basic processing. Returning non-2xx status codes may cause Plivo to retry the webhook delivery.
- Error Handling: Catches JSON parsing errors and other processing errors, logging them and returning appropriate HTTP status codes (400 for bad JSON, 500 for internal errors).
4. Configuring Plivo Webhooks for Your Next.js App
You need to tell Plivo where to send these webhook events. This is typically done by creating or configuring a Plivo Application.
- Navigate to Plivo Console: Go to Messaging -> Applications.
- Create or Edit an Application:
- Click "Add New Application".
- Give it a descriptive name (e.g., "Next.js WhatsApp App").
- Message URL: This is the crucial part. Enter the publicly accessible HTTPS URL for your webhook handler:
- Local Development: Start ngrok (ngrok http 3000) and copy the https forwarding URL. Your Message URL will be https://<your-ngrok-subdomain>.ngrok.io/api/plivo-webhook.
- Production (e.g., Vercel): Use your deployed application's URL: https://<your-vercel-app-name>.vercel.app/api/plivo-webhook.
- Method: Set to POST.
- (Optional) Configure Answer URL and other settings if you plan to use Plivo for voice calls with this application as well.
- Click "Create Application" or "Update Application".
- Associate Sender with Application:
- Go to Messaging -> WhatsApp Senders.
- Find your WhatsApp sender number and click "Edit".
- In the "Application" dropdown, select the Plivo Application you just created or updated.
- Click "Update Sender". This ensures incoming messages and status updates for this sender are routed to your webhook URL.
5. Error Handling, Logging, and Retry Strategies
Robust applications need solid error handling.
- API Route Errors: The API routes already include
try...catchblocks. - Log errors using console.error. In production, integrate a dedicated logging service (e.g., Sentry, Logtail, Datadog) for better aggregation, searching, and analysis.
- Return meaningful JSON error responses with appropriate HTTP status codes (4xx for client errors like invalid input, 5xx for server errors like failed Plivo client initialization or downstream issues). Avoid leaking sensitive internal details in error responses sent to the client.
- Plivo API Errors: The
catchblock in/api/send-whatsapp/route.jsspecifically handles errors fromclient.messages.create(). Log theerror.messageand potentiallyerror.error(which might contain Plivo-specific error details) for debugging. Consider theerror.statusCodeto understand the error type (e.g., 400 bad request, 401 auth error, 5xx server error). - Webhook Errors: The webhook handler logs processing errors. Ensure signature validation
failures are logged clearly, including why validation failed (e.g., missing header, calculation mismatch).
If your internal processing logic fails after receiving the webhook (e.g., database write
error), consider logging the error but still returning a
200 OKto Plivo to prevent unnecessary retries if the issue is internal and not Plivo's fault (assuming you can handle the failure asynchronously or it's non-critical). If the webhook should be retried because the failure was temporary (e.g., temporary DB unavailability), return a5xxerror code. - Retries:
- Outgoing Messages: For transient errors from the Plivo API (e.g., network issues,
temporary Plivo downtime resulting in 5xx errors), consider implementing a retry mechanism in the
/api/send-whatsapproute. Use libraries likeasync-retryfor exponential backoff.
npm install async-retry
import retry from 'async-retry';
try {
const response = await retry(
async (bail, attemptNumber) => {
console.log(`Attempt ${attemptNumber} to send message via Plivo...`);
try {
const apiResponse = await client.messages.create(payload);
console.log("Plivo API call successful.");
return apiResponse;
} catch (error) {
console.warn(`Plivo API call attempt ${attemptNumber} failed:`, error.message);
if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500) {
console.error(`Bailing on Plivo API call due to client error ${error.statusCode}.`);
bail(error);
return;
}
throw error;
}
},
{
retries: 3,
factor: 2,
minTimeout: 1000,
maxTimeout: 10000,
onRetry: (error, attempt) => console.warn(`Retrying Plivo API call (Attempt ${attempt}). Error: ${error.message}`)
}
);
console.log("Successfully sent message after retries (if any). Plivo Response:", response);
return NextResponse.json({
success: true,
message_uuid: response.messageUuid?.[0],
api_id: response.apiId,
message: response.message,
});
} catch (error) {
console.error("Plivo API Error after all retries or non-retryable error:", error);
const errorMessage = error.message || "Failed to send message via Plivo after retries.";
const errorStatus = error.statusCode || 500;
return NextResponse.json(
{ success: false, error: errorMessage, details: error.error },
{ status: errorStatus }
);
}
- Incoming Webhooks: Plivo automatically handles retries for webhooks if your endpoint
doesn't return
200 OKwithin a certain timeout. Ensure your endpoint is reliable and responds quickly. If processing might take longer than Plivo's timeout, acknowledge the webhook immediately (200 OK) and process the data asynchronously.
Looking to expand your messaging capabilities? Check out these related guides:
- Send SMS Messages with Plivo and Next.js - Learn the basics of SMS integration
- Building Two-Way Messaging with Plivo - Handle inbound SMS and create interactive conversations
- Implementing OTP Verification with Plivo - Add two-factor authentication to your app
For more information about Plivo's WhatsApp Business API, visit the official Plivo WhatsApp documentation.
You can send WhatsApp messages within a Next.js app by creating an API route that uses the Plivo Node.js SDK. This route will handle requests containing the destination number and message content, then securely interact with the Plivo API to send the WhatsApp message.
The Plivo WhatsApp Business API connects your Next.js application to the WhatsApp network, enabling programmatic sending and receiving of WhatsApp messages. This allows for automated communication, such as notifications, customer support, and interactive conversations, directly within your app.
Next.js is chosen for its server-side rendering capabilities, API routes for backend logic, and overall streamlined developer experience. Its popularity and robust features make it well-suited for integrating with the Plivo WhatsApp Business API.
Incoming WhatsApp messages are received via webhooks. You'll need to create a secure API route in your Next.js app that can handle POST requests from Plivo. Critically, this route must implement robust signature validation to ensure security.
Configure a Plivo Application in the Plivo console, providing the public HTTPS URL of your Next.js webhook API route. Use ngrok for local development or your deployed application's URL for production. Associate your Plivo WhatsApp sender number with this Application to route incoming messages and statuses to your webhook.
ngrok creates a secure tunnel to your local development server, providing a public HTTPS URL that Plivo can use to send webhooks during development. This allows you to test your webhook handling logic locally before deployment.
You'll need PLIVO_AUTH_ID, PLIVO_AUTH_TOKEN, and
PLIVO_WHATSAPP_SENDER_NUMBER in a .env.local file. These store your Plivo
credentials and the sender number, which are essential for the Plivo SDK and webhook security.
The Plivo Node.js SDK simplifies interaction with the Plivo REST API. It handles authentication, request formatting, and response parsing, making it easier to send messages and manage communication logic within your Next.js application.
Webhook signature validation is crucial for security. Consult the official Plivo documentation for the correct validation method. Implement and test this thoroughly before deploying to production. The provided placeholder code must be replaced with Plivo's recommended logic.
The provided /api/send-whatsapp route example demonstrates handling different message types,
including text, media, templates, interactive messages, and location data. Include validation and conditional
logic based on the 'type' field in the incoming request body to process each accordingly.
Plivo Applications are configurations in the Plivo console that define how Plivo interacts with your application. They specify webhook URLs, sender numbers, and other settings required for routing incoming messages and statuses correctly.
Implement comprehensive error handling using try-catch blocks, detailed logging, and potentially retry mechanisms. Consider integrating a dedicated logging service for production and handle Plivo-specific errors by inspecting the status code and error messages.
Use retry mechanisms with exponential backoff when dealing with transient errors from the Plivo API, such as network issues or temporary 5xx server errors. Do not retry on 4xx client errors, which indicate a problem with the request itself.
Node.js version 18 or later is recommended for compatibility with the Next.js framework and the Plivo Node.js SDK, ensuring optimal performance and access to the latest features.
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 β