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.
Build a Next.js App with Infobip WhatsApp Integration
This guide provides a complete walkthrough for integrating Infobip's WhatsApp Business API into a Next.js application. You will learn how to set up your environment, build an API endpoint to send WhatsApp messages using the Infobip Node.js SDK, create a basic frontend to interact with the API, and configure webhooks to receive incoming messages.
By the end of this tutorial, you will have a functional Next.js application capable of sending text messages via WhatsApp through Infobip and a basic setup for handling inbound messages, laying the groundwork for more complex conversational applications.
Project Overview and Goals
What We're Building:
We are 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:
This integration enables developers to programmatically send and receive WhatsApp messages, automating notifications, customer support interactions, alerts, or other communication workflows directly from their Next.js application.
Technologies Used:
@infobip-api/sdk
: The official Infobip Node.js SDK for interacting with their APIs.dotenv
: To manage environment variables securely.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 a similar tunneling service (likelocaltunnel
or Cloudflare Tunnels) for testing webhooks locally. Alternatively, deploy to a staging environment with a public URL.1. Setting Up the Project
Let's initialize a new Next.js project and install the necessary dependencies.
Create a Next.js App: Open your terminal and run the following command to create a new Next.js project with TypeScript:
When prompted, accept the defaults or configure ESLint, Tailwind CSS,
src/
directory, and App Router according to your preferences. This guide assumes the use of thesrc/
directory and App Router.Navigate to Project Directory:
Install Dependencies: We need the Infobip SDK and
dotenv
for managing environment variables.or using yarn:
Configure Environment Variables: Create a file named
.env.local
in the root of your project. This file will store your Infobip credentials securely. Never commit this file to version control.INFOBIP_API_KEY
andINFOBIP_BASE_URL
: Log in to your Infobip account. Navigate to the API Keys section (usually accessible from the developer settings or dashboard homepage). Generate a new API key if you don't have one. Your Base URL will also be displayed here. It typically looks likexxxxx.api.infobip.com
. (Note: UI navigation in the Infobip portal may change over time.)INFOBIP_WHATSAPP_SENDER
: This is the phone number you registered and connected to the WhatsApp Business API through the Infobip portal. Find it under the ""Channels and Numbers"" or ""WhatsApp"" section. (Note: UI navigation in the Infobip portal may change over time.)INFOBIP_WEBHOOK_SECRET
: Choose a strong, random string. You must use this later when configuring the webhook in the Infobip portal and implement signature verification in your webhook handler (Section 4 & 7) to ensure requests are genuinely from Infobip.Update
.gitignore
: Ensure.env.local
is listed in your.gitignore
file to prevent accidentally committing your secrets. The default Next.js.gitignore
usually includes it.2. Implementing Core Functionality: Sending Messages
We'll 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 the following code into
src/app/api/send-whatsapp/route.ts
. This code sets up an API endpoint that listens for POST requests, extracts the recipient number and message, and uses the Infobip SDK to send the WhatsApp message.Explanation:
next/server
and@infobip-api/sdk
.process.env
. We include basic checks to ensure they are present.Infobip
client instance is created using the API Key and Base URL. The comment explains why memoization might be beneficial.POST
handler function receives theNextRequest
.to
phone number andmessage
text.to
) is validated against a regex (e164Regex
) that checks for E.164 format (optional leading+
, followed by 11-15 digits). The error message guides the user on the expected format.infobip.channels.whatsapp.send()
is called with the required parameters:type
,from
,to
, andcontent
.try...catch
block handles potential errors during the API call, logging the error and returning a JSON error response with an appropriate status code.3. Building a Simple Frontend
Let's create a basic React component to interact with our API endpoint.
Modify the Homepage: Open
src/app/page.tsx
and replace its content with the following:Explanation:
'use client'
directive marks this as a Client Component, necessary for using hooks likeuseState
.phoneNumber
,message
,status
,isLoading
) manage the form inputs and feedback.handleSubmit
is triggered on form submission. It prevents the default form action, sets loading state, and makes afetch
request to our/api/send-whatsapp
endpoint.htmlFor
attributes on labels now correctly match theid
attributes of the corresponding input/textarea.?.
) is used when accessing themessageId
from the response data as a defensive measure against potential variations in the success response structure.status
message is updated accordingly.fetch
call is included.4. Integrating with Infobip: Receiving Messages (Webhook)
To receive incoming WhatsApp messages sent to your Infobip number, you need to set up a webhook. Infobip will send an HTTP POST request to a URL you provide whenever a message arrives.
Create the Webhook API Route File: Create a new file at
src/app/api/whatsapp-webhook/route.ts
.Implement the Webhook Handler: Paste the following code into
src/app/api/whatsapp-webhook/route.ts
. This handler includes essential signature verification logic.Explanation:
POST
handler receives the incoming request from Infobip.verifyInfobipSignature
function and logic to call it. This function uses Node.jscrypto
to perform HMAC SHA256 hashing (this needs verification against Infobip's specific documentation). It reads the raw request body, calculates the hash using yourINFOBIP_WEBHOOK_SECRET
, and compares it to the signature provided in theX-Infobip-Signature
header (header name also needs verification).request.json()
which consumes the body stream). Verification reads the body from a cloned request to avoid consuming the stream prematurely.payload.results
to extract sender (from
) and text message content. You'll need to adapt this based on the actual payload structure documented by Infobip for different message types.200 OK
response promptly to Infobip to acknowledge receipt. Failure to do so might cause Infobip to retry sending the webhook, leading to duplicate processing. Implement idempotency (e.g., checking message IDs) in your processing logic.Expose Local Endpoint (e.g., with
ngrok
): To test the webhook locally, Infobip needs a publicly accessible URL.Start your Next.js development server:
npm run dev
(usually runs on port 3000).In a new terminal window, run
ngrok
or your chosen tunneling tool:The tool will provide a public HTTPS URL (e.g.,
https://<random-string>.ngrok-free.app
). Copy this HTTPS URL.Production/Staging Note: For persistent testing or production, use a deployed URL (e.g., from Vercel, Netlify) or a more permanent tunneling solution if required during staging (like Cloudflare Tunnels).
Configure Webhook in Infobip Portal:
ngrok
or your deployment), appending your API route path:https://<your-public-url>/api/whatsapp-webhook
.INFOBIP_WEBHOOK_SECRET
from your.env.local
file here. This is required for the signature verification to work.5. 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
.6. 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.7. 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.8. 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{11,15}$
) enforces this structure.9. 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.10. 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).