Frequently Asked Questions
Use the provided Fastify backend service, which exposes API endpoints like /send/text and /send/template to send WhatsApp messages via Plivo. These endpoints allow you to send both simple text messages and more complex template-based messages using the Plivo Node.js SDK within a structured, maintainable Node.js application built with Fastify.
Fastify is a high-performance web framework for Node.js, known for its speed and extensibility. It was selected for this WhatsApp integration because it offers a developer-friendly experience with features like built-in validation, logging, and support for TypeScript, making it ideal for robust application development.
TypeScript adds static typing to JavaScript, which enhances code quality, maintainability, and developer experience. Using it with Node.js for this integration helps prevent errors during development due to type checking, thus increasing overall reliability of the service.
Use template messages when you need structured, pre-approved content for specific use cases, such as appointment reminders or order confirmations. Text messages are suitable for ad-hoc communication or simpler notifications. Plivo and WhatsApp have guidelines for template message approval.
Yes, the service includes a webhook endpoint (/webhooks/plivo) designed to receive incoming WhatsApp messages and status updates from Plivo. This enables two-way communication, which is essential for features like customer support and interactive messaging.
You need a Plivo account, a WhatsApp Business Account (WABA) linked to Plivo, and a WhatsApp-enabled phone number on your Plivo account. Once set up, you can use the Plivo API and the provided Node.js code to send and receive WhatsApp messages.
The /webhooks/plivo endpoint in the Fastify application receives incoming messages from Plivo's webhooks. The code then processes these messages, allowing you to implement actions like auto-replies, logging, or database updates. The example shows how to differentiate between incoming messages and message statuses.
The Plivo Node SDK simplifies interaction with the Plivo API, making it easier to send messages, manage numbers, and handle other communication tasks directly from your Node.js applications without complex API calls.
While not strictly required, Prisma, a modern ORM, is recommended along with PostgreSQL. Using a database helps store and retrieve WhatsApp messages, making logging and management functionalities within the application simpler and more organized.
Use the npm run dev command. This script uses nodemon to automatically restart the application whenever code changes are made. It uses ts-node to execute the application without needing to compile it manually.
The application is designed for containerization using Docker, which makes it easy to deploy it to various environments. The clear project structure, along with configurations for Docker, logging, and env variables, sets it up for deployment readiness.
The code provides a simple API key authentication mechanism using the x-api-key header. It's important to generate a strong, secure API key and keep it confidential, similar to the webhook secret. More robust authentication methods can be implemented based on your security needs.
The code includes a validatePlivoWebhook function which uses Plivo's signature validation (V3) method to verify that incoming webhook requests are from Plivo. The guide provides further instructions to enable the verification.
Environment variables store sensitive configuration data like Plivo API credentials, database URL, port number, and the API key for endpoint protection. The .env file is used to manage these locally, and should never be committed to version control. @fastify/env is used for safe loading and validation of environment variables.
This comprehensive guide shows you how to integrate Plivo WhatsApp messaging with Node.js and Fastify to build a production-ready API. Learn to send and receive WhatsApp Business messages, handle webhooks, implement authentication, and deploy with Docker—everything you need for enterprise-grade WhatsApp integration.
Build a Fastify backend service that exposes API endpoints to send text and template-based WhatsApp messages via Plivo. Include a webhook endpoint to receive incoming messages and status updates from Plivo, ensuring two-way communication. This setup solves the common need for programmatic WhatsApp interaction for customer support, notifications, and engagement campaigns.
This tutorial covers everything from initializing your Node.js project with TypeScript to implementing secure webhook handlers and deploying with Docker. Whether you're building a customer support chatbot, sending transactional notifications, or creating a WhatsApp marketing platform, this guide provides the foundation you need. For similar integrations, see our guides on Plivo SMS with Express and Twilio WhatsApp with Fastify.
Technologies Used:
plivopackage (v4.74.0 as of October 2025), not the deprecatedplivo-nodepackage. [Source: npm plivo package]dotenv/@fastify/env: For managing environment variables securely.pino-pretty: For readable development logs.@fastify/sensible: Adds sensible defaults and utility decorators.@fastify/rate-limit: For API rate limiting.@fastify/type-provider-typebox: For schema validation using TypeBox.System Architecture:
Prerequisites:
nvmfor managing Node versions. Note: Node.js v18 reached End-of-Life in April 2025 and should not be used. [Source: Node.js Release Schedule]ngrokor a similar tunneling service.Final Outcome:
A containerized Fastify application with API endpoints (
/send/text,/send/template) and a webhook receiver (/webhooks/plivo/whatsapp) for seamless WhatsApp communication via Plivo, complete with logging, basic security, and deployment readiness.1. Set up your Plivo WhatsApp Node.js project
Initialize your Node.js project using TypeScript and install Fastify along with essential dependencies.
1.1 Install Node.js and configure your environment:
Use Node Version Manager (
nvm) to manage Node.js versions for optimal compatibility with Fastify v5.macOS/Linux:
Windows: Download the installer from the Node.js website or use
nvm-windows. [Source: nvm-sh GitHub, latest version v0.40.3 as of October 2025]1.2 Project Initialization:
1.3 Project Structure:
Create the following directory structure:
Explanation:
src/: Contains all application logic written in TypeScript.dist/: Contains the compiled JavaScript code generated bytsc. Run the code from here in production.routes/: Separates API endpoint definitions for better organization.services/: Encapsulates logic for interacting with external services like Plivo or the database.schemas/: Holds JSON schema definitions used by Fastify for request validation.utils/: Contains reusable helper functions.server.ts: The main application file where the Fastify server is configured and started..env: Stores sensitive information like API keys. Use@fastify/envto load these..gitignore: Prevents committing sensitive files (.env,node_modules,dist).tsconfig.json: Configures the TypeScript compiler.1.4 Configuration Files:
.gitignore:.env.example(Create this file):.envfile by copying.env.exampleand fill in your actual credentials. Ensure.envis listed in.gitignore. Generate strong, unique values forPLIVO_WEBHOOK_SECRETandAPI_KEY.tsconfig.json(Modify the generated one):1.5 Run Scripts (
package.json):Add these scripts to your
package.jsonfile:build: Compiles TypeScript to JavaScript in thedistdirectory.start: Runs the compiled JavaScript application (for production).dev: Runs the application usingts-nodeandnodemonfor development, automatically restarting on file changes.test: Placeholder script. Implement a proper testing strategy (e.g., using Jest or Vitest).2. Implement Plivo WhatsApp messaging with Fastify
Set up the Fastify server and create the service responsible for interacting with Plivo.
2.1 Configure your Fastify server for WhatsApp messaging (
src/server.ts):Explanation:
initializePlivoClientfunction.envSchema: Defines expected environment variables using TypeBox for validation and type safety.FastifyInstanceto include the loadedconfigobject for type-safe access.buildServerfunction:pino-prettyin dev, JSON in prod).@fastify/envto load.envand validate variables.initializePlivoClient(server)immediately after config is loaded.@fastify/sensible./api/whatsapp./and/healthroutes.startfunction:buildServer.HOSTandPORTfrom config.setupGracefulShutdownafter the server successfully starts listening.setupGracefulShutdown): Implements handlers forSIGINTandSIGTERMto allow graceful server closure.start()to run the application.2.2 Create the Plivo WhatsApp service (
src/services/plivoService.ts):This service encapsulates all logic for interacting with the Plivo WhatsApp API, including sending text messages and template messages.
Explanation:
initializePlivoClientcreates a singleton Plivo client using credentials fromserver.config. It includes a check to ensure credentials exist. This is called once during server startup inserver.ts.sendWhatsAppTextMessage:server(for logging/config), recipientto, and messagetext.paramsfor the Plivo API call.try…catchfor Plivo API errors.sendWhatsAppTemplateMessage:templateobject conforming to Plivo'sTemplatetype.3. Build WhatsApp API endpoints with TypeScript validation
Define the API endpoints for sending messages and receiving webhooks.
3.1 Define WhatsApp message schemas with TypeScript (
src/schemas/whatsappSchemas.ts):Using
@fastify/type-provider-typeboxfor runtime validation and type safety.Explanation:
3.2 Create WhatsApp API routes with authentication (
src/routes/whatsappRoutes.ts):Explanation:
x-api-keyheader against the configuredAPI_KEY./send/textEndpoint: Accepts a text message request, validates input, calls the Plivo service, and returns a success response./send/templateEndpoint: Similar to text endpoint, but for template messages./webhooks/plivoEndpoint: Receives webhooks from Plivo. Differentiates between status updates and incoming messages based on payload structure. Acknowledges receipt immediately to prevent retries.4. Test your Plivo WhatsApp integration
Test your endpoints locally using curl or an API client like Postman.
4.1 Start the development server:
4.2 Send a text message:
4.3 Send a template message:
4.4 Test webhooks locally using ngrok:
Install and run ngrok to expose your local server:
Copy the HTTPS URL provided by ngrok (e.g.,
https://abc123.ngrok.io) and configure it in your Plivo console:https://abc123.ngrok.io/api/whatsapp/webhooks/plivoSend a WhatsApp message to your Plivo number and check your server logs for the incoming webhook.
5. Deploy your WhatsApp API with Docker
Containerize your application for consistent deployment across environments.
5.1 Create a
Dockerfile:5.2 Create a
.dockerignorefile:5.3 Build and run the Docker image:
5.4 Docker Compose (Optional):
Create a
docker-compose.ymlfor orchestrating multiple services:Run with:
6. WhatsApp integration best practices for production
6.1 Security:
@fastify/rate-limit.@fastify/cors.6.2 Logging and Monitoring:
6.3 Database Integration:
6.4 Error Handling:
6.5 Performance:
Troubleshooting
Common Issues:
.envfile containsPLIVO_AUTH_IDandPLIVO_AUTH_TOKENx-api-keyheader matchesAPI_KEYin.envnpm run buildand check for missing types or syntax errorsDebug Steps:
Next steps
validatePlivoWebhookhook with crypto-based verification.@fastify/rate-limitto protect your API endpoints.Related Resources: