Tutorials

Infobip SMS Webhooks with Next.js: Receive & Process Inbound Messages

Complete guide to building a Next.js webhook endpoint for receiving inbound SMS messages via Infobip. Includes authentication, error handling, Prisma storage, and production deployment.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 6, 2026 β€’ 14 min read

Developer Quick-Start: Complete guide to building a Next.js webhook endpoint for receiving inbound SMS messages via Infobip. Includes authentication, error handling, Prisma storage, and production deployment. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.

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:

  • Create a Next.js application with a dedicated API endpoint to receive incoming SMS messages from Infobip.
  • Securely handle Infobip credentials and webhook secrets.
  • Configure Infobip to route inbound messages (Mobile Originated – MO) to the Next.js webhook.
  • Implement basic security validation for incoming webhook requests.
  • Process and log incoming SMS data.
  • (Optional) Store received messages in a database using Prisma.
  • Provide instructions for local testing, deployment, and verification.

Technologies Used:

  • Next.js: React framework for building the web application and API endpoint. Chosen for its ease of development, built-in API routes, and robust ecosystem. (Requires Node.js 18.18 or later as of Next.js 15)
  • Node.js: The runtime environment for Next.js.
  • Infobip: The CPaaS provider used for sending and, crucially here, receiving SMS messages via webhooks. Official Documentation
  • Prisma (Optional): Modern ORM for database interaction. Chosen for its developer experience and type safety. (Prisma 5.x recommended)
  • Ngrok (for testing): Tool to expose local development servers to the internet for webhook testing.

System Architecture:

<!--
Replace this block with a static image or a textual description of the architecture:
End User --(Sends SMS)--> Infobip Platform --(Forwards MO SMS via HTTP POST)--> Next.js App / Webhook Endpoint --(Processes Request)--> [Optional Database]
The Next.js App sends a 200 OK response back to the Infobip Platform.
-->

Prerequisites:

  • An active Infobip account with a number capable of receiving SMS messages.
  • Node.js (v18.18 or later recommended for Next.js 15) and npm/yarn installed.
  • Basic understanding of JavaScript, Node.js, Next.js, and REST APIs.
  • Access to a terminal or command prompt.
  • (Optional) A database (e.g., PostgreSQL, MySQL, SQLite) if implementing the Prisma storage layer.
  • (Optional) Ngrok installed for local webhook testing.

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.

  1. 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.
   npx create-next-app@latest infobip-inbound-app --typescript --eslint --tailwind --src-dir --app --import-alias ""@/*""

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).

  1. Navigate to Project Directory:
   cd infobip-inbound-app
  1. 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 by create-next-app).
   # .env.local

   # Infobip Configuration (Obtain from Infobip Portal - see Section 4)
   # NOTE: BASE_URL and API_KEY are primarily needed for *sending* messages via the API.
   # They are not strictly required just to *receive* webhooks if you only implement inbound handling.
   # Include them if you plan to extend this app to send replies.
   INFOBIP_BASE_URL=your_infobip_api_base_url.api.infobip.com
   INFOBIP_API_KEY=YourInfobipApiKey

   # Webhook Security (Choose a strong, unique secret)
   # This MUST match the 'Password' you configure in Infobip's webhook Basic Auth settings.
   INFOBIP_WEBHOOK_SECRET=a_very_strong_and_secret_string_you_generate

   # (Optional) Database Connection (If using Prisma - see Section 6)
   # Example for PostgreSQL:
   DATABASE_URL=""postgresql://user:password@host:port/database?schema=public""
  • 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.
  1. Project Structure: The create-next-app command with the --app flag sets up the App Router structure. Our primary focus will be within the src/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

  1. Create the API Route File: Create a new file at src/app/api/infobip-webhook/route.ts. Next.js automatically maps files named route.ts within the app directory structure to API endpoints. This file will handle requests made to /api/infobip-webhook.
  2. Implement the Basic Handler: Add the following code to src/app/api/infobip-webhook/route.ts:
   import { NextRequest, NextResponse } from 'next/server';
   import logger from '@/lib/logger';

   interface InfobipIncomingMessage {
       messageId?: string;
       from?: string;
       to?: string;
       text?: string;
       keyword?: string;
       receivedAt?: string;
       cleanText?: string;
       smsCount?: number;

   }

   interface InfobipWebhookPayload {
       results: InfobipIncomingMessage[];
       messageCount: number;
       pendingMessageCount: number;
   }

   export async function POST(req: NextRequest) {
       logger.info('Received request on /api/infobip-webhook');

       try {


           const expectedSecret = process.env.INFOBIP_WEBHOOK_SECRET;
           const authHeader = req.headers.get('authorization');

           if (!expectedSecret) {
               logger.warn('INFOBIP_WEBHOOK_SECRET is not set in environment variables. Skipping webhook authentication.');

           } else if (!authHeader || !authHeader.toLowerCase().startsWith('basic ')) {
               logger.error('Missing or invalid Authorization header');
               return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
           } else {

               const encodedCreds = authHeader.split(' ')[1];
               if (!encodedCreds) {
                    logger.error('Invalid Authorization header format (missing credentials)');
                    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
               }
               const decodedCreds = Buffer.from(encodedCreds, 'base64').toString('utf-8');
               const [username, password] = decodedCreds.split(':');


               if (password !== expectedSecret) {
                    logger.error('Invalid webhook secret provided');
                    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
               }




               logger.info(`Webhook authentication successful for user: ${username}`);
           }


           const body: InfobipWebhookPayload = await req.json();
           logger.debug({ payload: body }, 'Webhook payload received');

           if (!body.results || !Array.isArray(body.results)) {
               logger.warn('Received invalid payload structure (missing or non-array results).');

               return NextResponse.json({ message: 'Acknowledged invalid payload structure' }, { status: 200 });
           }

           if (body.results.length === 0) {
                logger.info('Received webhook with empty results array.');

                return NextResponse.json({ message: 'Acknowledged empty payload' }, { status: 200 });
           }




           for (const message of body.results) {
               logger.info({ from: message.from, msgId: message.messageId }, `Processing message`);






           }




           return NextResponse.json({ message: 'Webhook received successfully' }, { status: 200 });

       } catch (error) {

           if (error instanceof SyntaxError) {

                logger.error('Failed to parse incoming JSON payload.', { error });
                return NextResponse.json({ error: 'Invalid JSON payload' }, { status: 400 });
           }


           logger.error('Error processing Infobip webhook', { error });







           return NextResponse.json({ message: 'Acknowledged, but internal processing error occurred.' }, { status: 200 });


       }
   }

   export async function GET(req: NextRequest) {
     logger.warn(`Received unsupported GET request on webhook endpoint.`);
     return NextResponse.json({ message: 'Method Not Allowed' }, { status: 405 });
   }
  • InfobipWebhookPayload / InfobipIncomingMessage: Interfaces defining the expected data structure. Added citation to check official Infobip documentation.
  • POST Function: Handles POST requests from Infobip. Next.js Route Handlers Documentation
  • Security Validation: Implements Basic Authentication per Infobip Authentication Methods, comparing the provided password against INFOBIP\_WEBHOOK\_SECRET.
  • Parsing: req.json() parses the incoming request body. Includes validation for body.results.
  • Processing Loop: Iterates through the results array.
  • Response Timing: Must respond within 2-3 seconds to prevent Infobip retries.
  • Logging: Uses structured logging (Section 5 setup).
  • Response Codes: Returns 200 OK on successful receipt/processing, 401 for auth failures, 400 for invalid JSON. Recommended 200 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
  • This is the URL you will configure in the Infobip platform.
  • Only the POST method is expected to receive message data. GET or other methods should return 405 Method Not Allowed.
  • Authentication: Basic Authentication Infobip API Authentication
  • The endpoint expects an Authorization: Basic <credentials> header.
  • The <credentials> part is a Base64 encoded string of username:password.
  • The password MUST be the value you set for INFOBIP\_WEBHOOK\_SECRET.
  • The required username MUST be verified in your Infobip webhook configuration.
  • Request Body (Expected from Infobip):
  • Content-Type: application/json
  • Structure (verify against Infobip MO SMS Documentation):
    {
      "results": [
        {
          "messageId": "ABC-123-XYZ",
          "from": "15551234567",
          "to": "15559876543",
          "text": "Hello there!",
          "cleanText": "Hello there!",
          "keyword": "HELLO",
          "receivedAt": "2023-10-27T10:30:00.123Z",
          "smsCount": 1

        }

      ],
      "messageCount": 1,
      "pendingMessageCount": 0
    }
  • Response Body (Sent back to Infobip):
  • Success (200 OK): Acknowledges receipt. Must be sent within 2-3 seconds.
    { "message": "Webhook received successfully" }
  • Authentication Error (401 Unauthorized): Incorrect or missing credentials.
    { "error": "Unauthorized" }
  • Bad Request Error (400 Bad Request): Malformed JSON or invalid payload structure.
    { "error": "Invalid JSON payload" }
  • 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:
  • HTTPS is required for production webhook URLs
  • Basic Authentication credentials must be configured in Infobip portal
  • Consider implementing request signature validation for additional security

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.

  1. Obtain Infobip Credentials (If Sending Replies):
  • Log in to your Infobip Portal.
  • Navigate to the API key management section (often under "Developers" or account settings).
  • Copy your API Key and Base URL. API Authentication Documentation
  • If you plan to send replies from your app, add these to your .env.local file (INFOBIP\_API\_KEY, INFOBIP\_BASE\_URL).
  • These are not strictly required just for receiving webhooks.
  1. Configure Inbound Message Routing (Webhook): The exact steps can vary slightly based on Infobip's UI updates, but generally involve:
  • Navigate to the "Numbers" section in your Infobip portal.
  • Select the specific number for receiving SMS.
  • Look for "Messaging Settings", "Forwarding Rules", or "Application Settings".
  • Find the section for Incoming Messages or Mobile Originated (MO) Messages.
  • Choose the option to forward messages to a URL (Webhook).
  • Enter Your Webhook URL: The publicly accessible URL of your deployed Next.js application (e.g., https://your-app-domain.com/api/infobip-webhook).
  • IMPORTANT: Must use HTTPS in production for security
  • During local development, use an ngrok URL or similar tunneling service
  • Configure Authentication (Critical for Security):
  • Select Basic Authentication.
  • Enter the Username as required by Infobip (verify in portal).
  • Enter the Password – use the exact same secret as INFOBIP\_WEBHOOK\_SECRET in your .env.local.
  • Save the configuration.
  1. Webhook Testing Checklist:
  • HTTPS URL configured (required for production)
  • Basic Auth credentials match between Infobip portal and .env.local
  • Webhook endpoint returns 200 OK within 2-3 seconds
  • Logging captures incoming requests for debugging
  • Error handling prevents crashes from malformed requests

5. Implementing Production-Ready Error Handling and Logging

Robust error handling and logging are vital for production applications.

  1. Error Handling Strategy:
  • The primary goal is to reliably acknowledge receipt to Infobip (200 OK) quickly after successful authentication (within 2-3 seconds).
  • Use try...catch blocks to capture errors during request processing.
  • Bad Requests (4xx): Return 400 Bad Request for malformed JSON, 401 Unauthorized for failed authentication, 405 Method Not Allowed for incorrect HTTP methods.
  • Server Errors (Internal Processing): For errors occurring after successful authentication and validation, log the error thoroughly. Recommended: Return 200 OK to acknowledge receipt and prevent retries for potentially persistent internal issues.
  • Infobip Retry Policy: Infobip retries webhook delivery on non-2xx responses. Design for quick acknowledgment and asynchronous processing.
  1. Logging: Use a structured logging library like pino or winston for production.
  • Install Pino:
     npm install pino pino-pretty

     yarn add pino pino-pretty
  • Setup Logger: Create src/lib/logger.ts:
     import pino from 'pino';

     const logger = pino({
       level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
       transport: process.env.NODE_ENV !== 'production'
         ? { target: 'pino-pretty', options: { colorize: true } }
         : undefined,
     });

     export default logger;
  • Use Logger in Webhook:
  • Use appropriate levels (debug, info, warn, error).
  • Log key events: request received, auth success/failure, message processing, errors.
  • Avoid logging full payloads at info level in production (PII concerns); use debug if necessary.
  1. Response Timing Best Practices:
  • Respond to Infobip within 2-3 seconds with 200 OK
  • Use asynchronous processing (message queues, background jobs) for slow operations
  • Monitor webhook response times in production
  • Implement timeout handling to prevent hanging requests

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.

  1. Install Prisma:
   npm install prisma --save-dev
   npm install @prisma/client

   yarn add prisma -D && yarn add @prisma/client
  1. Initialize Prisma:
   npx prisma init --datasource-provider postgresql

This creates a prisma directory with a schema.prisma file. Ensure your .env.local has the correct DATABASE_URL.

  1. Define Schema: Edit prisma/schema.prisma:

Prisma

   // prisma/schema.prisma

   generator client {
     provider = "prisma-client-js"
   }

   datasource db {
     provider = "postgresql" // Or your chosen provider
     url      = env("DATABASE_URL")
   }

   // Model to store incoming Infobip messages
   model IncomingMessage {
     id            String    @id @default(cuid())
     infobipMessageId String?   @unique // Infobip's message ID, prevents duplicates
     sender        String    // 'from' number
     recipient     String    // 'to' number (your Infobip number)
     messageText   String?   // SMS content
     keyword       String?   // Detected keyword, if any
     receivedAt    DateTime  // Timestamp when Infobip received it (UTC)
     processedAt   DateTime  @default(now()) // When your app processed it
     createdAt     DateTime  @default(now())
     updatedAt     DateTime  @updatedAt

     @@index([sender])
     @@index([receivedAt])
     @@index([infobipMessageId])
   }
  1. Apply Schema Migrations:
   npx prisma migrate dev --name init
   npx prisma generate
  1. Implement Data Access in Webhook:
  • Create a Prisma client instance (e.g., src/lib/prisma.ts):
     import { PrismaClient } from '@prisma/client';

     declare global {


       var prisma: PrismaClient | undefined;
     }

     export const prisma =
       global.prisma ||
       new PrismaClient({
         log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
       });

     if (process.env.NODE_ENV !== 'production') {
       global.prisma = prisma;
     }

     export default prisma;
  • Use the client in your API route:
     import { NextRequest, NextResponse } from 'next/server';
     import logger from '@/lib/logger';
     import prisma from '@/lib/prisma';

     import { Prisma } from '@prisma/client';

     export async function POST(req: NextRequest) {

         logger.info('Received request on /api/infobip-webhook');

         try {

             logger.info(`Webhook authentication successful.`);

             const body: InfobipWebhookPayload = await req.json();

             logger.debug({ payload: body }, 'Webhook payload received');

             if (body.results && body.results.length > 0) {

                 try {

                     await prisma.$transaction(async (tx) => {
                         for (const message of body.results) {
                             logger.info({ from: message.from, msgId: message.messageId }, `Processing message for storage`);


                             const messageData = {
                                 infobipMessageId: message.messageId,
                                 sender: message.from ?? 'unknown',
                                 recipient: message.to ?? 'unknown',
                                 messageText: message.text,
                                 keyword: message.keyword,

                                 receivedAt: message.receivedAt ? new Date(message.receivedAt) : new Date(),
                             };


                             await tx.incomingMessage.create({
                                 data: messageData,
                             });
                             logger.info({ msgId: message.messageId }, `Message stored successfully.`);


                         }
                     });
                      logger.info(`Successfully processed and stored ${body.results.length} message(s).`);
                 } catch (dbError) {
                     logger.error({ err: dbError }, ""Database transaction failed during message storage"");




                     return NextResponse.json({ message: 'Acknowledged, but failed to store message data.' }, { status: 200 });




                 }
             } else {
                 logger.info('Received webhook with empty or invalid results array.');
                 return NextResponse.json({ message: 'Acknowledged empty/invalid payload' }, { status: 200 });
             }


             return NextResponse.json({ message: 'Webhook received and processed successfully' }, { status: 200 });

         } catch (error) {

             if (error instanceof SyntaxError) {
                 logger.error('Failed to parse incoming JSON payload.', { error });
                 return NextResponse.json({ error: 'Invalid JSON payload' }, { status: 400 });
             }








             logger.error('Unhandled error processing Infobip webhook', { error });

             return NextResponse.json({ message: 'Acknowledged, but unexpected internal error occurred.' }, { status: 200 });


         }
     }

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.

  1. Install and Start Ngrok:
   npm install -g ngrok

   npm run dev

   ngrok http 3000
  1. Configure Infobip with Ngrok URL:
  • Copy the HTTPS forwarding URL from ngrok (e.g., https://abc123.ngrok.io)
  • Update your Infobip webhook configuration with https://abc123.ngrok.io/api/infobip-webhook
  • Ensure Basic Auth credentials are configured
  1. Send Test SMS:
  • Send an SMS to your Infobip number
  • Monitor your terminal for incoming webhook requests
  • Verify 200 OK responses and proper message processing

8. Deploying Your SMS Webhook to Production

Deploy your Next.js application to a production environment with HTTPS support:

Recommended Platforms:

  • Vercel: Native Next.js support, automatic HTTPS, serverless functions
  • Railway: Full-stack deployment with database support
  • AWS/GCP/Azure: Enterprise-grade infrastructure with scalability

Deployment Checklist:

  • Environment variables configured (INFOBIP\_WEBHOOK\_SECRET, DATABASE\_URL)
  • HTTPS enabled (required for production webhooks)
  • Database migrations applied (npx prisma migrate deploy)
  • Webhook URL updated in Infobip portal
  • Monitoring and logging configured
  • Error alerting setup for failed webhooks

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:

  • Use serverless functions (Vercel, AWS Lambda) for automatic scaling
  • Implement message queues (Redis, RabbitMQ) for asynchronous processing
  • Deploy multiple webhook instances behind a load balancer
  • Monitor response times and optimize database queries
  • Implement rate limiting to prevent abuse

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:

  • Implement automated SMS reply logic based on keywords or commands
  • Add conversation tracking for multi-turn dialogues
  • Integrate with CRM systems or notification services
  • Set up monitoring dashboards (Datadog, New Relic, Sentry)
  • Implement message queueing for high-volume scenarios

For sending outbound SMS replies, refer to the Infobip Send SMS API documentation.

Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)

If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.

curl -X POST https://api.sendsmsnokyc.com/messages \
  -H "x-api-key: $SMSROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["+14155551234"],
    "channel": ["sms"],
    "body": "Your verification code is 482910"
  }'
  • Instant onboarding: No KYC paperwork or sales queues β€” grab an API key and fund with crypto (BTC/USDT) or card.
  • Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
  • Transparent global pricing: Compare exact per-country termination rates on our live pricing page.

Ship Global SMS in One API Call

Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.

Explore SMSRoute Developers β†’