Frequently Asked Questions
Implement Infobip's delivery report webhooks to receive real-time status updates within your Next.js application. This involves setting up a callback URL in your app that Infobip will send POST requests to, containing delivery status details like 'DELIVERED', 'UNDELIVERABLE', or 'FAILED'.
An Infobip delivery report webhook (or callback) is an HTTP POST request sent by Infobip to your application. It contains real-time updates on the delivery status of your SMS messages, providing information beyond the initial 'sent' status from the API.
Infobip callbacks provide more reliable delivery confirmation than simply relying on the initial 'sent' status. Network issues or invalid numbers can prevent delivery, and callbacks offer real-time updates on these situations, enabling you to take appropriate action.
Set up Infobip delivery report webhooks when you need reliable tracking of SMS message delivery. This is particularly important for critical messages like two-factor authentication, appointment reminders, or order confirmations where knowing the delivery outcome is essential.
Yes, while the guide uses PostgreSQL with Prisma, the core concepts can be applied to other databases. The key is to have a database schema that can store message status, including the Infobip messageId
for matching incoming webhook data.
Use the Infobip Node.js SDK within a Next.js Server Action or API route, along with your API key and base URL, to send SMS messages. Make sure to store the messageId
returned by Infobip for later tracking with the webhooks.
The Infobip messageId
is a unique identifier for each SMS message you send. It's crucial for correlating delivery reports received via webhooks with the specific message they refer to in your database.
Secure your webhook callback route using either Basic Authentication or custom header verification. Configure one of these methods in the Infobip portal and implement corresponding verification logic in your Next.js API route using environment variables for security credentials.
The article recommends using the latest version of Next.js with the App Router, which is the current standard. While the code examples use NextAuth.js v4, you might consider Auth.js (formerly NextAuth.js v5) for new App Router projects due to better integration.
Infobip webhooks can deliver status updates for multiple messages in a single request. Your callback handler should iterate through the 'results' array in the payload and process each message status update individually.
You'll need Node.js v18 or later, npm or yarn, an Infobip account with API access, a database (PostgreSQL, SQLite, MySQL, or similar), and a basic understanding of Next.js, React, API routes, and asynchronous JavaScript.
NextAuth simplifies user authentication in Next.js. Integrating it allows you to easily associate sent SMS messages with specific users in your application, which is often a common requirement.
Common status values include 'PENDING', 'SENT', 'DELIVERED_TO_HANDSET', 'FAILED_UNDELIVERABLE', 'EXPIRED', and 'REJECTED'. The exact values and their meanings are available in the official Infobip documentation.
Reliably sending SMS messages is crucial for many applications, but knowing if they were actually delivered is equally important. Relying solely on the initial ""sent"" status from an API isn't enough. Network issues, invalid numbers, or carrier blocks can prevent delivery.
This guide details how to build a robust system in Next.js using NextAuth for authentication and Infobip for SMS delivery. We'll implement Infobip's delivery report webhooks (callbacks) to receive real-time updates on message status directly within our application, persisting this information for tracking and potential automated actions.
By the end of this guide, you will have:
messageId
.Prerequisites:
Technology Stack:
System Architecture
Here's a high-level overview of how the components interact:
messageId
returned by Infobip into the database, marking the initial status as ""PENDING"" or ""SENT"".messageId
, and updates itsdeliveryStatus
,errorDescription
(if any), anddeliveredAt
timestamp.Diagram Summary: The diagram illustrates the flow starting with a user action in the Next.js app, leading to an SMS send request via the Infobip API. The app records the initial message status. Infobip processes the SMS and sends a delivery report via webhook to a callback route in the Next.js app. This callback route verifies the request, finds the message in the database using the message ID, updates its status, and responds to Infobip.
1. Setting up the Project
Let's initialize a new Next.js project and install necessary dependencies.
1. Initialize Next.js Project:
Open your terminal and run:
Select your preferred options when prompted. We're using the App Router (
--app
), TypeScript, ESLint, Tailwind CSS, thesrc/
directory, and import aliases.2. Install Dependencies:
We need
next-auth
for authentication, Prisma for database interaction, and the Infobip SDK.next-auth
: Core library.@next-auth/prisma-adapter
: Links NextAuth sessions/users to your Prisma database.@prisma/client
: Prisma's database client.@infobip-api/sdk
: Official Infobip Node.js SDK.prisma
(dev dependency): Prisma CLI for migrations and studio.bcrypt
,@types/bcrypt
: For the Credentials provider password hashing example.3. Initialize Prisma:
Set up Prisma with PostgreSQL (you can choose another database if preferred).
This creates a
prisma
directory with aschema.prisma
file and a.env
file for your database connection string.4. Configure Environment Variables:
Open the
.env
file created in the previous step. It will initially contain theDATABASE_URL
. Add placeholders for Infobip credentials, NextAuth secrets, and webhook security options.DATABASE_URL
: Update this with your actual database connection details. Ensure the databaseinfobip_tracker
exists.NEXTAUTH_SECRET
: Essential for securing NextAuth sessions/JWTs. Generate a strong random string.NEXTAUTH_URL
: The canonical URL of your application. Crucial for redirects and callbacks.INFOBIP_API_KEY
&INFOBIP_BASE_URL
: Obtain these from your Infobip account dashboard (API Key Management). The Base URL is specific to your account.INFOBIP_WEBHOOK_USER
andINFOBIP_WEBHOOK_PASSWORD
for Basic Authentication orINFOBIP_WEBHOOK_SECRET
for header-based verification, matching the security method you choose in the Infobip portal (see Section 5).Important: Add
.env
to your.gitignore
file to avoid committing secrets. Create a.env.example
file listing the variables needed without their values.5. Project Structure:
Your
src/
directory will look something like this initially:Create the
lib
directory and theprisma.ts
file.6. Initialize Prisma Client:
Create a singleton instance of the Prisma client to avoid creating too many connections in development.
2. Creating the Database Schema
Define the database models needed for users (via NextAuth adapter) and tracking message status.
1. Define Schema:
Update your
prisma/schema.prisma
file. Prisma's NextAuth adapter requires specific models (User
,Account
,Session
,VerificationToken
). We'll add our customMessageStatus
model.MessageStatus
with fields to store Infobip'smessageId
, the recipient, message body, the evolvingstatus
, potential error details, and relevant timestamps.infobipMessageId
is marked@unique
as it's the primary identifier we'll use to match incoming webhooks. We also added an index@@index([infobipMessageId])
.User
model.passwordHash
on theUser
model if using the Credentials provider example.2. Run Database Migration:
Apply these schema changes to your database.
This command will:
prisma/migrations/
.You can inspect your database structure using
npx prisma studio
if desired.3. Implementing NextAuth
Configure NextAuth to handle user sessions. We'll use JWT sessions and add the
userId
to the token/session object so we can associate sent messages with users.1. Create NextAuth API Route:
Create the catch-all API route handler for NextAuth.
PrismaAdapter
to store user/session data in our database.bcrypt
on user creation/update) and use a library likebcrypt.compare
within theauthorize
function. The placeholder check is highly insecure and MUST be replaced.strategy: 'jwt'
.jwt
andsession
callbacks are used to add theuser.id
to the session object, making it available in your application..env
.2. Create Auth Provider Component:
Wrap your application layout with the NextAuth
SessionProvider
.3. Update Root Layout:
Apply the
AuthProvider
in your root layout.Now you should have a basic authentication setup ready. Create a login page (
src/app/login/page.tsx
or similar) and implement login/logout UI elements usingsignIn()
andsignOut()
fromnext-auth/react
.4. Sending SMS and Storing Initial Status
Let's create a mechanism (e.g., a Server Action) to send an SMS via Infobip and record its initial status.
1. Create Infobip Client Utility:
Centralize the Infobip client initialization.
2. Create Server Action:
Use a Server Action to handle sending SMS.
'use server'
: Marks this as a Server Action module.zod
.infobip.channels.sms.send
.from
field.messageId
Extraction & DB Storage: Extracts the crucialmessageId
and stores the initial message details in theMessageStatus
table.3. Create Frontend Component (Example):
Create a form to trigger the Server Action.
Add
<SendSmsForm />
to an authenticated page.5. Implementing the Infobip Callback Handler
This route receives status updates from Infobip.
1. Configure Infobip Webhook:
ngrok
(e.g.,https://YOUR_NGROK_SUBDOMAIN.ngrok.io/api/infobip/callback
). For production:https://yourdomain.com/api/infobip/callback
.INFOBIP_WEBHOOK_USER
andINFOBIP_WEBHOOK_PASSWORD
in your.env
.X-Webhook-Secret
) with the value ofINFOBIP_WEBHOOK_SECRET
from your.env
.2. Create the Callback API Route:
.env
variables.InfobipDeliveryReportPayload
based on common fields (refer to official docs for specifics).results
array, as Infobip can send multiple updates in one request.infobipMessageId
and updates its status, error details, anddeliveredAt
timestamp. UsestoUpperCase()
for status consistency.200 OK
NextResponse to acknowledge receipt to Infobip.With these components in place, your Next.js application can now send SMS messages via Infobip and reliably track their final delivery status using webhooks. Remember to deploy your application and update the Infobip webhook URL to your production endpoint. Use
ngrok
or a similar tool for testing callbacks during local development.