Frequently Asked Questions
First, create a Next.js app and an API route file at 'src/app/api/infobip-webhook/route.ts'. Then, set up environment variables in '.env.local', including your Infobip credentials and a webhook secret. This API route will handle incoming SMS messages from Infobip.
The webhook URL format is your deployed app's public URL plus the API route path. For example: 'https://your-app-domain.com/api/infobip-webhook'. Use ngrok for local testing.
Basic Authentication secures your webhook by requiring a username and password. This prevents unauthorized access and ensures only Infobip can send data to your endpoint. You'll set the password to match your 'INFOBIP_WEBHOOK_SECRET'.
Use Prisma if you need to store incoming SMS messages for later analysis, history tracking, or to manage stateful conversations. The article provides a schema example for storing message data.
Yes, you can use ngrok to create a temporary public URL that forwards requests to your local development server. This allows you to test the integration before deployment.
Secure your webhook with Basic Authentication by setting the 'Authorization' header in your requests. The username is often your API Key ID or a designated string, while the password is your 'INFOBIP_WEBHOOK_SECRET'. Verify the exact username Infobip requires.
The webhook expects a JSON payload with 'results', 'messageCount', and 'pendingMessageCount'. 'results' is an array of incoming messages, each containing details like 'messageId', 'from', 'to', 'text', and 'receivedAt'.
The provided code example iterates through the 'results' array in the webhook payload. Inside the loop, you can implement your logic to store the message, check for keywords, trigger replies, or enqueue for background processing.
Returning a 200 OK response promptly acknowledges successful receipt of the webhook to Infobip, preventing unnecessary retries. Do this even if internal processing encounters errors after authentication, but log such errors thoroughly.
The 'INFOBIP_WEBHOOK_SECRET' environment variable stores a secret string you generate. It acts as the password for Basic Authentication, securing your webhook. This secret must match the password configured in your Infobip webhook settings.
Implement robust error handling using try-catch blocks. For client-side errors, return 4xx status codes. For internal errors after successful authentication, return 200 OK to acknowledge receipt, but log the error for later investigation.
This integration uses Next.js for the app and API route, Node.js as the runtime, Infobip as the CPaaS provider, and optionally Prisma for database interaction and ngrok for local testing.
You'll need an active Infobip account, Node.js and npm/yarn installed, basic understanding of JavaScript and related technologies, and optionally a database and ngrok.
The article provides a Prisma schema example that includes fields for the sender, recipient, message text, timestamp, and more. You can adjust this schema based on your specific needs.
How to Receive Inbound SMS Messages with Infobip and Next.js
This guide provides a complete walkthrough for building a Next.js application capable of receiving and processing inbound SMS messages sent via the Infobip platform. By implementing a webhook endpoint, your application can handle replies, commands, or any incoming SMS traffic directed to your Infobip number, enabling true two-way messaging conversations.
We'll cover setting up your Next.js project, creating the API route to act as a webhook receiver, configuring Infobip to forward messages, handling basic security, processing incoming messages, storing them (optionally), and deploying the application.
Project Goals:
Technologies Used:
System Architecture:
Prerequisites:
1. Setting Up Your Next.js Project for SMS Webhooks
Let's start by creating a new Next.js project and setting up the basic structure and environment variables.
Create a Next.js App: Open your terminal and run the following command, replacing
infobip-inbound-app
with your desired project name. We'll use TypeScript for better type safety.Follow the prompts (you can accept the defaults). This command sets up a new Next.js project using the App Router (
--app
), TypeScript, ESLint, and Tailwind CSS (optional but common).Navigate to Project Directory:
Set up Environment Variables: Create a file named
.env.local
in the root of your project. This file will store sensitive information like API keys and secrets. It's crucial not to commit this file to version control (it's included in the default.gitignore
created bycreate-next-app
).INFOBIP_BASE_URL
&INFOBIP_API_KEY
: Obtain these from your Infobip account dashboard. Needed if you extend the app to send SMS replies.INFOBIP_WEBHOOK_SECRET
: This is a secret you define. It acts as the password for Basic Authentication to secure your webhook endpoint. Configure this exact value in the Infobip portal (Section 4).DATABASE_URL
: Add this only if you plan to implement the database layer (Section 6). Adjust the format based on your chosen database.Project Structure: The
create-next-app
command with the--app
flag sets up the App Router structure. Our primary focus will be within thesrc/app/api/
directory where we'll create the webhook endpoint.2. Implementing the Core Functionality (Webhook Endpoint)
The core of this application is the API route that listens for incoming POST requests from Infobip containing Mobile Originated (MO) SMS messages. Infobip MO SMS Documentation
Create the API Route File: Create a new file at
src/app/api/infobip-webhook/route.ts
. Next.js automatically maps files namedroute.ts
within theapp
directory structure to API endpoints. This file will handle requests made to/api/infobip-webhook
.Implement the Basic Handler: Add the following code to
src/app/api/infobip-webhook/route.ts
:InfobipWebhookPayload
/InfobipIncomingMessage
: Interfaces defining the expected data structure. Added citation to check official Infobip documentation.POST
Function: HandlesPOST
requests from Infobip. Next.js Route Handlers DocumentationINFOBIP_WEBHOOK_SECRET
.req.json()
parses the incoming request body. Includes validation forbody.results
.results
array.200 OK
on successful receipt/processing_401
for auth failures_400
for invalid JSON. Recommended200 OK
for internal processing errors after receipt to avoid unnecessary retries.3. Understanding the Webhook API Contract
The API route
src/app/api/infobip-webhook/route.ts
serves as the API layer for receiving inbound SMS. Here's a summary of its contract:Endpoint:
POST /api/infobip-webhook
POST
method is expected to receive message data.GET
or other methods should return405 Method Not Allowed
.Authentication: Basic Authentication Infobip API Authentication
Authorization: Basic <credentials>
header.<credentials>
part is a Base64 encoded string ofusername:password
.password
MUST be the value you set forINFOBIP_WEBHOOK_SECRET
.username
MUST be verified in your Infobip webhook configuration.Request Body (Expected from Infobip):
application/json
Response Body (Sent back to Infobip):
Webhook Retry Behavior: Infobip will retry webhook delivery if it doesn't receive a
2xx
response within timeout (typically a few seconds). Design your endpoint to respond quickly and use asynchronous processing for complex operations.Security Requirements:
4. Configuring Infobip SMS Forwarding to Your Webhook
This is where you configure Infobip to send incoming SMS messages to your newly created webhook endpoint.
Obtain Infobip Credentials (If Sending Replies):
.env.local
file (INFOBIP_API_KEY
,INFOBIP_BASE_URL
).Configure Inbound Message Routing (Webhook): The exact steps can vary slightly based on Infobip's UI updates, but generally involve:
https://your-app-domain.com/api/infobip-webhook
).ngrok
URL or similar tunneling serviceINFOBIP_WEBHOOK_SECRET
in your.env.local
.Webhook Testing Checklist:
.env.local
5. Implementing Production-Ready Error Handling and Logging
Robust error handling and logging are vital for production applications.
Error Handling Strategy:
try...catch
blocks to capture errors during request processing.400 Bad Request
for malformed JSON,401 Unauthorized
for failed authentication,405 Method Not Allowed
for incorrect HTTP methods.200 OK
to acknowledge receipt and prevent retries for potentially persistent internal issues.Logging: Use a structured logging library like
pino
orwinston
for production.src/lib/logger.ts
:debug
,info
,warn
,error
).info
level in production (PII concerns); usedebug
if necessary.Response Timing Best Practices:
200 OK
6. Storing SMS Messages with Prisma (Optional Database Layer)
Storing incoming messages enables history tracking, analysis, and stateful conversations. We'll use Prisma 5.x.
Install Prisma:
Initialize Prisma:
This creates a
prisma
directory with aschema.prisma
file. Ensure your.env.local
has the correctDATABASE_URL
.Define Schema: Edit
prisma/schema.prisma
:Apply Schema Migrations:
Implement Data Access in Webhook:
src/lib/prisma.ts
):7. Testing Your Infobip Webhook Locally with Ngrok
Before deploying to production, test your webhook endpoint locally using ngrok to expose your development server to the internet.
Install and Start Ngrok:
Configure Infobip with Ngrok URL:
https://abc123.ngrok.io
)https://abc123.ngrok.io/api/infobip-webhook
Send Test SMS:
8. Deploying Your SMS Webhook to Production
Deploy your Next.js application to a production environment with HTTPS support:
Recommended Platforms:
Deployment Checklist:
INFOBIP_WEBHOOK_SECRET
,DATABASE_URL
)npx prisma migrate deploy
)Frequently Asked Questions (FAQ)
How quickly must my webhook respond to Infobip?
Your webhook endpoint must return a 200 OK response within 2-3 seconds to prevent Infobip from retrying the delivery. For complex processing, acknowledge receipt immediately and use background jobs or message queues for asynchronous processing.
What happens if my webhook is down?
Infobip will retry webhook delivery on non-2xx responses according to their retry policy. Implement proper error handling and monitoring to minimize downtime and ensure you don't lose messages during outages.
Can I use API Keys instead of Basic Auth for webhooks?
For webhook authentication, Infobip requires Basic Authentication as configured in the portal. API Keys are used when your application makes outbound API calls to Infobip (e.g., sending SMS replies). Reference: Infobip API Authentication
How do I handle duplicate webhook deliveries?
Use the
infobipMessageId
field as a unique identifier and implement idempotency checks. In the Prisma schema provided, this field has a@unique
constraint to prevent duplicate message storage.Do I need HTTPS for local testing?
While HTTPS is required for production webhooks, you can use ngrok or similar tunneling services for local development. Ngrok automatically provides HTTPS endpoints that forward to your local server.
What's the difference between MO and MT messages?
MO (Mobile Originated) messages are inbound SMS sent from end users to your number - these arrive via webhooks. MT (Mobile Terminated) messages are outbound SMS you send from your application to end users via the Infobip Send SMS API.
How do I scale my webhook to handle high volumes?
Consider these approaches:
Summary and Next Steps
You've now built a production-ready Next.js webhook endpoint for receiving inbound SMS messages via Infobip. Your application can:
✅ Receive and authenticate webhook requests from Infobip
✅ Process Mobile Originated (MO) SMS messages
✅ Store message data in a database (optional)
✅ Handle errors gracefully and log events
✅ Scale to production traffic
Next Steps:
For sending outbound SMS replies, refer to the Infobip Send SMS API documentation.