Frequently Asked Questions
Create a Next.js API route (/api/send-bulk-sms) that handles POST requests containing recipient phone numbers and message text. This route interacts with the Infobip SMS API using Axios to dispatch messages. Refer to the provided code example for a complete implementation guide.
The `/sms/2/text/advanced` endpoint in the Infobip API is used for sending bulk SMS messages. It provides flexibility for managing multiple recipients, customizing sender IDs, and tracking delivery reports. This endpoint is central to the provided Next.js integration.
The Infobip Base URL (e.g., xxxxx.api.infobip.com) is unique to your account and region. It directs your requests to the correct Infobip API server, ensuring secure communication. You must configure this URL in your Next.js project's environment variables.
Use the `notifyUrl` parameter when you need real-time delivery reports for your SMS messages. Set its value to a dedicated webhook endpoint in your Next.js app. Infobip will send POST requests to this URL with delivery status updates for each message.
Yes, Prisma is recommended for storing and managing recipient lists, as well as logging sent messages and delivery statuses. The schema provided in the guide includes examples for Recipient, BulkSend, and MessageLog tables. Configure Prisma with PostgreSQL or your preferred database.
Obtain your API Key from your Infobip account dashboard. Store this key securely in a `.env.local` file in your Next.js project root. Then, access it in your code using `process.env.INFOBIP_API_KEY`.
Axios, a promise-based HTTP client, simplifies making API requests to Infobip from your Next.js application. It handles sending the POST request to the Infobip endpoint with necessary headers and data.
Implement a `try...catch` block around your Axios requests to the Infobip API. Log detailed error information (status, headers, response body) to the server. Return appropriate JSON error messages and HTTP status codes to the client.
Infobip's `/sms/2/text/advanced` endpoint expects an array of objects, each with a `to` property containing a phone number in E.164 format. The provided code example demonstrates how to format the request body for sending bulk SMS.
Create a new API route in your Next.js application (e.g., /api/infobip-webhook). This route will receive POST requests from Infobip. Provide the public URL of this route as the `notifyUrl` in your Infobip API request payload.
You'll need Node.js and npm/yarn, an active Infobip account with API access, basic Next.js/React knowledge, and familiarity with REST APIs. A code editor and Git are recommended but not strictly required.
The project leverages Next.js for its API routes, Infobip SMS API for message delivery, Node.js as the runtime environment, and Axios for HTTP requests. Optionally, Prisma can be used for database interactions and Vercel for deployment.
Retry API requests only on transient errors like network timeouts (504) or temporary Infobip server issues (503). Do not retry on client errors (4xx) such as invalid input or authentication failures. Implement exponential backoff and limit retry attempts.
Logging responses allows you to track successful and failed message sends, identify potential issues with recipient numbers or API connectivity, and monitor overall system performance. Use structured logging and consider a dedicated logging service for production.
This guide provides a complete walkthrough for building a system capable of sending bulk or broadcast SMS messages using Infobip's API within a Next.js application. We will cover everything from initial project setup to deployment, monitoring, and best practices for a production-ready implementation.
By the end of this tutorial, you will have a Next.js application with a secure API endpoint that can accept a list of recipients and a message, and then reliably dispatch these messages via the Infobip SMS API.
Project Goals:
Technology Stack:
sms/2/text/advanced
endpoint for its flexibility in handling multiple destinations.System Architecture:
Note: The webhook flow (bottom right) for receiving delivery reports via
notifyUrl
is optional but highly recommended for achieving full observability of message delivery statuses.Prerequisites:
1. Setting up the Project
Let's initialize a new Next.js project and set up the basic structure and environment.
1.1 Initialize Next.js Project
Open your terminal and run the following command:
Follow the prompts. We recommend selecting:
src/
directory: Yes (good practice for organization)Navigate into your new project directory:
1.2 Install Dependencies
We need
axios
to make HTTP requests to the Infobip API.1.3 Environment Variables
Create a file named
.env.local
in the root of your project. This file will store sensitive credentials and configuration. Never commit this file to version control.INFOBIP_API_KEY
: Your secret API key from Infobip.INFOBIP_BASE_URL
: Your unique base URL provided by Infobip (e.g._xxxxx.api.infobip.com
).INFOBIP_DEFAULT_SENDER_ID
: A default sender ID (alphanumeric or numeric) to use if not specified in the request. Check Infobip documentation and local regulations for sender ID requirements.Ensure your
.gitignore
file includes.env.local
:1.4 Project Structure (App Router)
Your relevant structure within the
src/app/
directory will look something like this:2. Implementing Core Functionality (API Route)
We'll create the API route that receives the list of recipients and the message content_ then interacts with the Infobip API.
Create the file
src/app/api/send-bulk-sms/route.js
:Explanation:
NextResponse
for API responses andaxios
.validateInput
Helper: Performs basic checks on the incoming request body structure and types. This should be expanded based on specific needs (e.g., stricter phone number validation using libraries likelibphonenumber-js
).POST
Handler: This is the main function executed when aPOST
request hits/api/send-bulk-sms
.validateInput
helper. Returns a 400 Bad Request error if validation fails./sms/2/text/advanced
).recipients
array from the request to Infobip's requireddestinations
array of objects ({ to: phoneNumber }
).messages
array payload according to the Infobip Send SMS API documentation.notifyUrl
(for delivery reports) orbulkId
.Authorization
header. Note: Infobip usesApp <API_KEY>
for newer keys andApiKey <API_KEY>
for older ones. Check your Infobip dashboard or try both if one fails. Also includesContent-Type
andAccept
headers.axios.post
to send the request.try...catch
block to capture errors during the API call.3. Building a Complete API Layer
The previous section already created our core API endpoint. This section details its usage and testing.
API Endpoint:
POST /api/send-bulk-sms
Request Body (JSON):
recipients
: (Required) An array of strings, each representing a phone number in international E.164 format (e.g.,+14155552671
).text
: (Required) The content of the SMS message as a string.senderId
: (Optional) The alphanumeric or numeric sender ID to display to the recipient. Defaults toINFOBIP_DEFAULT_SENDER_ID
from.env.local
if not provided.Success Response (Example - Status 200 OK):
bulkId
: An identifier assigned by Infobip (or your custom one if provided) for this batch send request. Useful for fetching logs or reports later.messages
: An array containing the status for each individual message sent within the bulk request.to
: The recipient's phone number.status
: An object indicating the initial status of the message submission (e.g.,PENDING
,REJECTED
). See Infobip Status Codes for details.messageId
: A unique identifier for this specific message, crucial for tracking delivery status via webhooks (notifyUrl
).Error Response Examples:
Testing with cURL:
Replace placeholders (
YOUR_NEXTJS_URL
, phone numbers, text,YOUR_SENDER_ID
) with your actual values. Run your Next.js app locally (npm run dev
oryarn dev
).Testing with Postman:
POST
.http://localhost:3000/api/send-bulk-sms
(or your deployed URL).4. Integrating with Infobip (Credentials)
This section details how to obtain the necessary credentials from Infobip.
4.1 Obtain API Key and Base URL
.env.local
asINFOBIP_API_KEY
.xxxxx.api.infobip.com
.https://
) and store it in your.env.local
asINFOBIP_BASE_URL
.4.2 Secure Storage
.env.local
: As configured in Step 1, this file keeps credentials out of your codebase and version control.4.3 Infobip Dashboard Configuration (Optional but Recommended)
notifyUrl
): To get real-time updates on message delivery status (delivered, failed, expired), you need to:/api/infobip-webhook
) capable of receiving POST requests from Infobip.notifyUrl
field when sending messages via the Infobip API (see the commented-out line inroute.js
).notifyContentType: 'application/json'
to receive reports in JSON format.5. Error Handling, Logging, and Retry Mechanisms
Our API route already includes basic error handling and logging. Let's enhance it.
5.1 Consistent Error Handling
The current
try...catch
block inroute.js
provides a good foundation:5.2 Enhanced Logging
For production, consider using a dedicated logging library or service instead of just
console.log
/console.error
.pino
,winston
offer structured logging, different log levels (debug, info, warn, error), and log rotation.Example (Conceptual - using a hypothetical logger):
5.3 Retry Mechanisms
Retrying failed bulk sends automatically can be complex and potentially costly.
504
, temporary Infobip server issues503
). Do not retry on client errors (4xx
) like invalid input or authentication failure.bulkId
), retrying the whole batch might be feasible. If the initial POST succeeds but some messages are later reported asFAILED
vianotifyUrl
, retrying individual failed messages requires more state management (trackingmessageId
s and their final statuses).notifyUrl
, log the delivery reports to understand final delivery success/failure.5.4 Testing Error Scenarios
/api/send-bulk-sms
.INFOBIP_API_KEY
in.env.local
to an invalid value and send a request. Expect a 401 error.recipients
array. Check the Infobip response forREJECTED
statuses.msw
or Jest mocks) to simulate network errors or specific Infobip error responses (5xx
) during integration tests.6. Creating a Database Schema (Optional Enhancement)
While not strictly required for sending, a database is crucial for managing recipients, tracking sends, and storing delivery statuses in a real-world application. We'll outline a basic schema using Prisma.
6.1 Setup Prisma
This creates a
prisma
directory with aschema.prisma
file and updates.env
(or.env.local
) with aDATABASE_URL
. Configure your database connection string there.6.2 Define Schema (
prisma/schema.prisma
)6.3 Apply Schema
Run the migration command to create the tables in your database:
6.4 Integrate with API Route (Conceptual)
Modify
src/app/api/send-bulk-sms/route.js
to interact with Prisma:This integration is illustrative. A production implementation requires careful handling of recipient mapping (phone number to ID), transaction management, and performance optimization for database lookups.