Frequently Asked Questions
Create an API route in your Next.js app that uses the Infobip SDK to send WhatsApp messages. This route should handle POST requests containing the recipient's phone number and the message content. The provided code example utilizes the '@infobip-api/sdk' and environment variables for secure credential management. A simple frontend form can then interact with this API route.
The Infobip WhatsApp Business API is a service provided by Infobip, a Communications Platform as a Service (CPaaS) provider. It enables developers to programmatically send and receive WhatsApp messages, integrating this communication channel directly into applications like the Next.js app demonstrated in this guide.
Next.js, a React framework, simplifies full-stack application development, making it an excellent choice for building a WhatsApp integration. It offers features like API routes for backend logic, server-side rendering, and a streamlined developer experience, as shown in the tutorial.
WhatsApp enforces a 24-hour window for free-form messages initiated by businesses. After this period, you must use pre-approved Template Messages. Consult Infobip's documentation for sending these messages, as they require a specific format ('type: 'template'') and pre-registered template names.
Yes, by setting up a webhook. Configure a dedicated API route in your Next.js app (e.g., '/api/whatsapp-webhook') and provide this URL to Infobip. They will send an HTTP POST request to this endpoint every time a message is received, triggering your handling logic. Be sure to implement robust security measures, especially webhook signature verification, to protect your application.
You'll need to create an API route in your Next.js application specifically to handle incoming webhook requests from Infobip. This route should parse the incoming message data and process it according to your application's needs, such as saving it to a database or triggering a reply. Critically, ensure that your implementation includes webhook signature verification to maintain security.
E.164 is an international standard for phone number formatting. It ensures consistent and unambiguous representation, generally consisting of a '+' followed by the country code and subscriber number, without any spaces or dashes. For instance, a US number would be formatted as +14155552671, and a UK number as +447123456789.
Webhook signature verification is paramount for security. Consult Infobip's documentation for their exact specifications. The tutorial provides a template using Node.js's 'crypto' library involving HMAC SHA256 hashing. You'll need to confirm the header name (e.g., 'X-Infobip-Signature'), algorithm, and encoding with their official documentation.
Before starting, you will need Node.js and npm/yarn installed. A crucial step is to set up environment variables for your Infobip API Key and Base URL, as outlined in the guide.
Use a tool like ngrok to expose your local development server to the internet, providing a public URL for your webhook. This allows Infobip to send requests to your application during development. Send a test WhatsApp message through your application's frontend, and reply to that message from WhatsApp to test the inbound webhook functionality.
These credentials are located within your Infobip account portal. After logging in, navigate to the API Keys Management section (usually accessible from the Developer settings or main dashboard), where you can generate and manage your API key. Your Base URL is generally also displayed here.
You will need INFOBIP_API_KEY
, INFOBIP_BASE_URL
, INFOBIP_WHATSAPP_SENDER
, and INFOBIP_WEBHOOK_SECRET
. These should be stored in a .env.local
file and never committed to version control.
Validating inputs protects your application from vulnerabilities and ensures that data is correctly formatted. The tutorial demonstrates basic validation for the recipient's phone number (E.164 format) and the presence of a message body, along with enhanced E.164 validation.
Platforms like Vercel are well-suited for Next.js deployments. Make sure to configure your environment variables on the chosen platform, update the webhook URL in the Infobip portal to your production URL after deployment, and consider setting up CI/CD for automated build and deployment processes.
WhatsApp Business API Integration with Next.js and Infobip
Integrate Infobip's WhatsApp Business API into a Next.js application. This guide covers environment setup, API endpoints for sending WhatsApp messages using the Infobip Node.js SDK, frontend implementation, and webhook configuration for receiving incoming messages.
Build a functional Next.js application that sends text messages via WhatsApp through Infobip and handles inbound messages, creating the foundation for conversational applications.
Project Overview and Goals
What We're Building:
A Next.js application that includes:
/api/send-whatsapp
) that accepts a phone number and message text, then uses the Infobip SDK to send a WhatsApp message./api/whatsapp-webhook
) to receive incoming message notifications from Infobip.Problem Solved:
Enables developers to programmatically send and receive WhatsApp messages, automating notifications, customer support interactions, alerts, and communication workflows directly from Next.js applications.
Technologies Used:
@infobip-api/sdk
: Official Infobip Node.js SDK for API interaction.dotenv
: For secure environment variable management.System Architecture:
<!-- Mermaid diagram visualizing system architecture was removed for standard Markdown compatibility -->
(Ensure your rendering environment supports Mermaid diagrams for the above visualization)
Prerequisites:
ngrok
or similar tunneling service (localtunnel
, Cloudflare Tunnels) for local webhook testing, or staging environment with public URL.Setting Up the Project
Initialize a new Next.js project and install dependencies.
Create a Next.js App: Run this command to create a Next.js project with TypeScript:
Accept defaults or configure ESLint, Tailwind CSS,
src/
directory, and App Router. This guide assumessrc/
directory and App Router (Next.js 13+).Navigate to Project Directory:
Install Dependencies: Install the Infobip SDK and
dotenv
for environment variables.or using yarn:
Configure Environment Variables: Create
.env.local
in the project root. This file stores Infobip credentials securely. Never commit this file to version control.INFOBIP_API_KEY
andINFOBIP_BASE_URL
: Log in to Infobip. Navigate to API Keys (usually in developer settings or dashboard). Generate a new API key if needed. Your Base URL appears here (typicallyxxxxx.api.infobip.com
).INFOBIP_WHATSAPP_SENDER
: This is the phone number registered and connected to WhatsApp Business API through Infobip. Find it under "Channels and Numbers" or "WhatsApp" section. Note: WhatsApp Business Account verification typically takes 1-3 business days.INFOBIP_WEBHOOK_SECRET
: Choose a strong, random string. Use this when configuring webhooks in Infobip portal and implement signature verification in your webhook handler (Sections 4 & 7) to ensure requests are genuinely from Infobip.Update
.gitignore
: Ensure.env.local
is in.gitignore
to prevent committing secrets. Default Next.js.gitignore
usually includes it.Implementing Core Functionality: Sending Messages
Create an API route that handles sending WhatsApp messages via the Infobip SDK.
Create the API Route File: Create a new file at
src/app/api/send-whatsapp/route.ts
.Implement the Sending Logic: Paste this code into
src/app/api/send-whatsapp/route.ts
:Explanation:
next/server
and@infobip-api/sdk
.process.env
with basic presence checks.Infobip
client instance using API Key and Base URL. Memoization comment explains potential optimization.POST
handler receivesNextRequest
.to
phone number andmessage
text.infobip.channels.whatsapp.send()
with required parameters.try...catch
handles errors, logging and returning appropriate status codes.Building a Simple Frontend
Create a basic React component to interact with the API endpoint.
Modify the Homepage: Open
src/app/page.tsx
and replace content with:Explanation:
'use client'
marks this as Client Component for using hooks.handleSubmit
prevents default form action, sets loading state, makesfetch
request to/api/send-whatsapp
.htmlFor
attributes match corresponding inputid
attributes.try...catch
handles errors, logging and returning appropriate status codes.Integrating with Infobip: Receiving Messages (Webhook)
Configure a webhook to receive incoming WhatsApp messages. Infobip sends HTTP POST requests to your URL when messages arrive.
Create the Webhook API Route File: Create a new file at
src/app/api/whatsapp-webhook/route.ts
.Implement the Webhook Handler: Paste this code into
src/app/api/whatsapp-webhook/route.ts
:Explanation:
POST
handler receives incoming requests from Infobip.verifyInfobipSignature
function for HMAC SHA256 signature verification using Node.jscrypto
. This MUST be adapted based on Infobip's specific documentation for exact header name, algorithm, and encoding.request.json()
). Verification reads from cloned request to avoid consuming stream.payload.results
to extract sender and text content. Adapt based on Infobip's documented payload structure.200 OK
promptly to acknowledge receipt. Failure causes Infobip retries and potential duplicates. Implement idempotency by checking message IDs.Expose Local Endpoint (e.g., with
ngrok
): Test webhook locally with public URL.Start Next.js dev server:
npm run dev
(typically port 3000).In new terminal, run
ngrok
:Copy public HTTPS URL (e.g.,
https://<random>.ngrok-free.app
).Production Note: Use deployed URL (Vercel, Netlify) or permanent tunneling solution for staging.
Configure Webhook in Infobip Portal:
https://<your-public-url>/api/whatsapp-webhook
.INFOBIP_WEBHOOK_SECRET
value from.env.local
. Required for signature verification.Verification and Testing
Now, let's test both sending and receiving messages.
Start the Application: If it's not already running, start your Next.js app:
Test Sending:
http://localhost:3000
.+14155552671
or447123456789
) in the ""Recipient Phone Number"" field. You can use your own number for testing.npm run dev
for logs from the/api/send-whatsapp
route.Test Receiving (Webhook):
npm run dev
is running. You should see logs from the/api/whatsapp-webhook
route:ngrok
web interface (usuallyhttp://localhost:4040
) or your tunneling tool's interface to inspect the incoming HTTP request details, including headers likeX-Infobip-Signature
.Error Handling, Logging, and Retries
try...catch
blocks. For production:zod
for schema validation.console.log
is used for simplicity. For production:200 OK
or encounters network issues. Store message IDs (message.messageId
from the payload) and check for duplicates before processing critical actions.Security Features
.env.local
and ensure this file is in.gitignore
. Use platform-specific environment variable management for deployment (e.g., Vercel Environment Variables, AWS Secrets Manager).to
,message
) and from webhooks. Use libraries likezod
for schema validation on API routes./api/send-whatsapp
,/api/whatsapp-webhook
) from abuse by implementing rate limiting. Tools like@upstash/ratelimit
or platform features (e.g., Vercel's IP blocking/rate limiting) can be used.ngrok
provide this locally, and deployment platforms like Vercel handle it automatically.Handling Special Cases (WhatsApp Specific)
type: 'text'
), which only works within this window or as a reply to an incoming user message. Refer to Infobip's documentation on sending Template Messages for sending messages outside the window. You'll need to use a different payload structure (type: 'template'
) and provide the registered template name and placeholders.type: 'text'
). Infobip supports various types (images, documents, audio, video, location, interactive messages like buttons and lists). Refer to the Infobip SDK documentation and API reference for payload structures for different types.+14155552671
,447123456789
). This typically includes an optional+
followed by the country code and the subscriber number, without spaces or dashes. Our validation regex (^\+?\d{1,15}$
) enforces this structure.Deployment and CI/CD
INFOBIP_API_KEY
,INFOBIP_BASE_URL
,INFOBIP_WHATSAPP_SENDER
, andINFOBIP_WEBHOOK_SECRET
in your chosen platform's environment variable settings. Do not hardcode them.npm run build
oryarn build
.https://your-app-domain.com/api/whatsapp-webhook
). Ensure the secret key is also correctly configured there.Troubleshooting and Caveats
.env.local
is missing, not loaded correctly, or the environment variables (INFOBIP_API_KEY
,INFOBIP_BASE_URL
) are misspelled or undefined in the current environment (especially check deployment environment variables).to
number in the send request strictly follows E.164 format (e.g.,+14155552671
,447123456789
). The API route includes validation, but double-check the input.ngrok
or deployed URL +/api/whatsapp-webhook
) is correctly configured in the Infobip portal.npm run dev
) or deployment is running.ngrok
's web interface (http://localhost:4040
) or your tunneling tool's logs for incoming requests.INFOBIP_WEBHOOK_SECRET
in your.env.local
(and deployment environment) exactly matches the secret configured in the Infobip portal.X-Infobip-Signature
?), hashing algorithm (sha256
?), and encoding (hex
?) used in theverifyInfobipSignature
function against Infobip's official documentation. The provided function is a template.to
ormessage
in the request body, or invalid phone number format. Check the API route's logs for specific error messages.error.response?.data
) logged in thecatch
block of the/api/send-whatsapp
route for specific error details from Infobip (e.g., authentication failure, insufficient funds, invalid sender).Frequently Asked Questions (FAQ)
Q: What Next.js and Node.js versions are required? A: Next.js 13+ with App Router support and Node.js v18.x or v20.x LTS are required. Earlier versions lack current security patches and App Router features.
Q: How long does WhatsApp Business Account verification take? A: Infobip's WhatsApp Business Account verification typically takes 1-3 business days. You cannot send messages until verification completes.
Q: What is the WhatsApp 24-hour messaging window? A: WhatsApp allows free-form messages only within 24 hours of the user's last message to your business. Outside this window, you can only send pre-approved Template Messages. This guide covers free-form text messages (
type: 'text'
) valid within the 24-hour window.Q: How do I send Template Messages outside the 24-hour window? A: Use
type: 'template'
in your send request with a registered template name and parameters. Templates must be pre-approved by WhatsApp through Infobip. See Infobip's Template Message documentation.Q: What phone number format does WhatsApp require? A: Use E.164 international format: optional '+' followed by 1-15 digits total (country code + subscriber number). Examples:
+14155552671
(US),447123456789
(UK). The corrected regex validates this properly.Q: Can I send media (images, videos, documents) via WhatsApp? A: Yes. Infobip supports images, documents, audio, video, location, and interactive messages (buttons, lists). Change
type
parameter and provide appropriatecontent
structure. See Infobip SDK documentation for payload formats.Q: How do I verify the webhook signature? A: The provided
verifyInfobipSignature
function is a template. Consult Infobip's webhook security documentation for exact header name, hashing algorithm, and encoding. Implementing this correctly is critical for production security.Q: What are the rate limits for sending WhatsApp messages? A: Rate limits depend on your Infobip account tier and WhatsApp Business Account status. Newly verified accounts typically start with lower limits (80-1000 messages/24 hours) that increase based on quality and volume. Check Infobip dashboard for your specific limits.
Q: Do I need user consent to send WhatsApp messages? A: Yes. You must obtain proper user opt-in before initiating conversations or sending promotional messages. Comply with WhatsApp Business policies and local regulations (GDPR, TCPA, etc.).
Q: How do I handle webhook retries and duplicates? A: Implement idempotency by storing processed message IDs (
message.messageId
from payload) in your database. Check IDs before processing to prevent duplicate actions. Infobip retries webhooks if it doesn't receive timely 200 OK responses.Q: Can I test webhooks without deploying or using ngrok? A: For local development, tunneling tools (
ngrok
,localtunnel
, Cloudflare Tunnels) are necessary since Infobip requires publicly accessible HTTPS URLs. For persistent testing, deploy to staging environment (Vercel preview deployments work well).Q: What's the difference between this and SMS integration? A: WhatsApp requires Business Account verification, supports richer media types, has the 24-hour window rule, requires Template Messages for proactive outreach, and typically offers better engagement rates. SMS has simpler setup, no 24-hour restrictions, but limited to 160-character text (or concatenated segments).
Q: How do I track message delivery status? A: Add
notifyUrl
parameter to your send request with your delivery report webhook URL. Infobip sends POST requests to this URL with delivery status updates (sent, delivered, read, failed).Q: Is this code production-ready? A: This tutorial provides a foundation. For production, add: robust input validation (
zod
), comprehensive error handling, retry mechanisms with job queues, structured logging (Winston
/Pino
), monitoring (Datadog
/Sentry
), rate limiting, proper webhook signature verification per Infobip docs, and database for message tracking.