Developer Quick-Start: A guide on building a Node.js backend to send SMS via Infobip, receive delivery status via webhooks, store updates, and push them to the frontend using Server-Sent Events (SSE). 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 Node.js backend system that sends SMS messages via Infobip, receives delivery status updates through webhooks, stores these updates, and pushes them in real-time to a connected frontend using Server-Sent Events (SSE). This enables you to provide immediate feedback to users about the status of their messages.
Project Goals:
- Send SMS messages programmatically using the Infobip API.
- Receive asynchronous delivery status reports from Infobip via webhooks.
- Persist message status information in a database.
- Push real-time status updates to specific frontend clients using SSE.
- Build a robust, scalable, and maintainable solution.
Target Audience: Developers familiar with Node.js, Express, REST APIs, and basic frontend concepts (React/Vue).
Technologies Used:
- Backend: Node.js, Express
- SMS Provider: Infobip API
- Real-time Communication: Server-Sent Events (SSE)
- Database: PostgreSQL (with Prisma ORM)
- HTTP Client: Axios
- Environment Variables: dotenv
- Development Tooling: nodemon (optional), ngrok (for local webhook testing)
Why these technologies?
- Node.js/Express: A popular, performant, and well-suited stack for building API backends and handling asynchronous operations like webhooks.
- Infobip: A robust communication platform offering reliable SMS delivery and detailed status reporting via webhooks.
- SSE: A simple and efficient W3C standard for pushing data from the server to the client over a single HTTP connection, ideal for status updates without the complexity of WebSockets.
- PostgreSQL/Prisma: A powerful relational database and a modern ORM that simplifies database interactions, migrations, and type safety.
- Axios: A widely-used, promise-based HTTP client for making requests to the Infobip API.
ngrok: Essential for exposing your local development server to the internet so Infobip can reach your webhook endpoint.
System Architecture:
+-------------+ +-----------------+ +-----------------+ +---------------+
| Frontend |<----->| Node.js/Express|<----->| Infobip |<----->| Mobile Device |
| (React/Vue) | | Backend | | Platform | | (Recipient) |
+-------------+ +-----------------+ +-----------------+ +---------------+
| /|\ | | | | |
| | SSE | Send SMS Request | | Send SMS |
| +----------------+ | +-------------->|
| | | |
| | Store Initial Status | Receive SMS |
| | (e.g., PENDING) | |
| V | |
| +----------+ | Status Update |
| | Database | | (e.g., DELIVERED) |
| | (Postgres) |<------------------------+
| +----------+ | |
| ^ | |
| Update Status | Webhook Notification | |
| /|\ +--------------------------+ |
| | Push Update | | |
+--+-----------------+ | |
SSE Connection | |
(listens for status changes) | |
- Frontend: Initiates the SMS send request, establishes an SSE connection to listen for status updates related to its request.
- Node.js Backend:
- Receives the send request.
- Generates a unique correlationId.
- Sends the SMS via Infobip API.
- Stores initial message details (including correlationId and Infobip's messageId) in the database.
- Provides an SSE endpoint (/sse-status/:correlationId) for the frontend to connect to.
- Provides a webhook endpoint (/infobip-webhook) for Infobip to send status updates.
- When a webhook is received: validates it, updates the corresponding message status in the database, and pushes the update via SSE to the relevant client connection.
- Infobip: Receives the SMS request, attempts delivery, and sends status updates (DELIVERED, FAILED, etc.) to the configured backend webhook URL.
- Database: Stores the state of each message, linking the internal correlationId to Infobip's messageId and the latest delivery status.
Prerequisites:
- Node.js and npm (or yarn) installed.
- An Infobip account (Free trial is sufficient, but note limitations).
- Access to a PostgreSQL database (local or cloud-based).
- ngrok installed for local development webhook testing. (Note: Free ngrok provides temporary URLs. For persistent URLs during development, consider paid ngrok or alternatives like localtunnel. In production, you will use your server's actual public URL.)
- Basic understanding of REST APIs and asynchronous JavaScript.
1. Setting up the Project
Let's initialize our Node.js project and install the necessary dependencies.
1.1 Create Project Directory:
mkdir infobip-status-backend
cd infobip-status-backend
1.2 Initialize npm Project:
npm init -y
This creates a package.json file.
1.3 Install Dependencies:
npm install express axios dotenv cors sse-channel uuid @prisma/client
npm install --save-dev nodemon prisma
- express: Web framework for Node.js.
- axios: Promise-based HTTP client.
- dotenv: Loads environment variables from a .env file.
- cors: Enables Cross-Origin Resource Sharing (necessary if your frontend is on a different domain/port).
- sse-channel: Simple library for managing Server-Sent Events channels.
- uuid: To generate unique correlation IDs.
- @prisma/client: The Prisma database client (required at runtime).
- nodemon (dev): Utility that monitors for changes and automatically restarts the server.
- prisma (dev): The Prisma CLI for database migrations and management.
1.4 Initialize Prisma:
npx prisma init --datasource-provider postgresql
This command does two things:
- Creates a prisma directory with a schema.prisma file. This is where you define your database schema.
- Creates a .env file in the root directory to store environment variables, including your database connection string.
1.5 Configure .env:
Open the generated .env file and update the DATABASE_URL. Also, add placeholders
for Infobip credentials and other settings.
.env
# .env
# Prisma Database Connection
# Example for local PostgreSQL: postgresql://USER:PASSWORD@HOST:PORT/DATABASE
DATABASE_URL="postgresql://postgres:yourpassword@localhost:5432/infobip_status?schema=public"
# Infobip Credentials
INFOBIP_BASE_URL="YOUR_INFOBIP_BASE_URL" # e.g., xyz.api.infobip.com (Find this in your Infobip account)
INFOBIP_API_KEY="YOUR_INFOBIP_API_KEY" # Find this in your Infobip account
# Server Configuration
PORT=3001
# This will be the public URL ngrok provides for your webhook during development
WEBHOOK_PUBLIC_URL="YOUR_NGROK_FORWARDING_URL" # e.g., https://abcd-1234.ngrok.io
# Optional: Secret for basic webhook validation
WEBHOOK_SECRET="a-very-secure-secret-string"
DATABASE_URL: Replace with your actual PostgreSQL connection string.INFOBIP_BASE_URL,INFOBIP_API_KEY: You'll get these from your Infobip dashboard (Account Settings -> API Keys).PORT: The port your Express server will run on.WEBHOOK_PUBLIC_URL: Leave this blank for now. We'll fill it when running ngrok.WEBHOOK_SECRET: A secret string you'll share only with Infobip (if using secret validation) to verify incoming webhooks.
1.6 Configure package.json Scripts:
Add development scripts to your package.json:
{
"scripts": {
"start": "node src/server.js",
"dev": "nodemon src/server.js",
"prisma:migrate": "prisma migrate dev --name init",
"prisma:generate": "prisma generate"
}
}
- start: Runs the application normally.
- dev: Runs the application using nodemon for auto-restarts.
- prisma:migrate: Applies database schema changes.
- prisma:generate: Generates the Prisma Client based on your schema.
1.7 Project Structure:
Create the following directory structure within your project root:
infobip-status-backend/
βββ prisma/
β βββ schema.prisma
βββ src/
β βββ config/
β β βββ index.js
β βββ controllers/
β β βββ messageController.js
β βββ middleware/
β β βββ webhookValidation.js
β βββ routes/
β β βββ index.js
β β βββ messageRoutes.js
β βββ services/
β β βββ databaseService.js
β β βββ infobipService.js
β β βββ sseService.js
β βββ utils/
β β βββ logger.js
β βββ server.js
βββ .env
βββ .gitignore
βββ package.json
config: Loads and exposes environment variables.controllers: Handles incoming HTTP requests, interacts with services, and sends responses.middleware: Request handling middleware (like webhook validation).routes: Defines API endpoints and maps them to controller functions.services: Contains business logic (interacting with Infobip, database, SSE).utils: Utility functions like logging.server.js: Sets up the Express app, middleware, and starts the server.
1.8 Basic Server Setup (src/server.js):
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const config = require('./config');
const routes = require('./routes');
const { initializeSSE } = require('./services/sseService');
const logger = require('./utils/logger');
const app = express();
app.use(cors());
app.use(express.json({ limit: '5mb' }));
initializeSSE(app);
app.use('/api', routes);
app.get('/health', (req, res) => {
res.status(200).send('OK');
});
app.use((err, req, res, next) => {
logger.error('Unhandled Error:', err);
res.status(500).json({ message: 'Internal Server Error' });
});
app.listen(config.port, () => {
logger.info(`Server running on port ${config.port}`);
logger.info(`Infobip Webhook URL should be configured to point to: ${config.webhookPublicUrl}/api/messages/webhook`);
if (!config.webhookPublicUrl || config.webhookPublicUrl === "YOUR_NGROK_FORWARDING_URL") {
logger.warn('WEBHOOK_PUBLIC_URL not set in .env. Run ngrok and update .env or Infobip configuration.');
}
});
module.exports = app;
1.9 Config Loader (src/config/index.js):
require('dotenv').config();
const config = {
port: process.env.PORT || 3001,
infobip: {
baseUrl: process.env.INFOBIP_BASE_URL,
apiKey: process.env.INFOBIP_API_KEY,
},
databaseUrl: process.env.DATABASE_URL,
webhookPublicUrl: process.env.WEBHOOK_PUBLIC_URL,
webhookSecret: process.env.WEBHOOK_SECRET,
};
if (!config.infobip.baseUrl || !config.infobip.apiKey) {
console.error('FATAL ERROR: Infobip Base URL or API Key not configured in .env');
process.exit(1);
}
if (!config.databaseUrl) {
console.error('FATAL ERROR: DATABASE_URL not configured in .env');
process.exit(1);
}
module.exports = config;
1.10 Logger Utility (src/utils/logger.js):
const logger = {
info: (...args) => console.log('[INFO]', ...args),
warn: (...args) => console.warn('[WARN]', ...args),
error: (...args) => console.error('[ERROR]', ...args),
debug: (...args) => console.debug('[DEBUG]', ...args),
};
module.exports = logger;
Note: The provided logger.js is extremely basic. For production applications, it is strongly
recommended to use a dedicated logging library like Winston or Pino. These libraries offer essential features
such as configurable log levels, structured logging (e.g., JSON), multiple transports (console, file, external
services), log rotation, and better performance.
2. Database Schema and Setup
Define the database schema using Prisma and apply it to your database.
2.1 Define Database Schema (prisma/schema.prisma):
We need a table to store the status of each message we send.
Prisma
// prisma/schema.prisma
generator client {
provider = ""prisma-client-js""
}
datasource db {
provider = ""postgresql""
url = env(""DATABASE_URL"")
}
model MessageStatus {
id String @id @default(uuid()) // Internal unique ID
correlationId String @unique // Our own ID to link frontend request <-> Infobip message
infobipMessageId String? // The ID returned by Infobip when sending
phoneNumber String // Recipient phone number
messageText String? // Optional: store message text
status String // e.g., PENDING, SENT, DELIVERED, FAILED, UNDELIVERABLE, REJECTED
statusGroup String? // e.g., PENDING, SENT, DELIVERED, FAILED, UNDELIVERABLE
statusDescription String? // Detailed description from Infobip
errorCode Int? // Infobip error code if applicable
errorMessage String? // Infobip error message if applicable
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([infobipMessageId]) // Index for quick lookup on webhook callback
@@index([createdAt])
}
- correlationId: A UUID we generate before sending the SMS. This is crucial for linking the initial request to subsequent webhook updates and the specific SSE connection.
- infobipMessageId: The ID Infobip returns after successfully accepting the message for sending. We use this to match incoming webhooks.
- status, statusGroup, statusDescription, errorCode, errorMessage: Fields to store details from Infobip's delivery reports.
2.2 Apply Database Migrations:
Run the migration command to create the MessageStatus table in your database. Prisma will prompt
you to name the migration (e.g., init).
npx prisma migrate dev --name init
If prompted, confirm that you want to create the migration and apply it. This updates your database schema.
2.3 Generate Prisma Client:
Ensure your Prisma Client is up-to-date with the schema:
npx prisma generate
3. Core Services Implementation
Implement the services for database interactions, managing SSE connections, and sending SMS via Infobip.
3.1 Database Service (src/services/databaseService.js):
Create a service to handle database interactions using Prisma Client.
const { PrismaClient } = require('@prisma/client');
const logger = require('../utils/logger');
const prisma = new PrismaClient({
});
async function saveInitialMessageStatus(data) {
try {
const message = await prisma.messageStatus.create({
data: {
correlationId: data.correlationId,
phoneNumber: data.phoneNumber,
messageText: data.messageText,
status: 'PENDING_SEND',
},
});
logger.info(`Initial status saved for correlationId: ${data.correlationId}`);
return message;
} catch (error) {
logger.error(`Error saving initial message status for ${data.correlationId}:`, error);
throw error;
}
}
async function updateMessageStatusPostSend(correlationId, infobipResponse) {
const messageInfo = infobipResponse?.messages?.[0];
if (!messageInfo || !messageInfo.messageId) {
logger.warn(`Could not extract messageId from Infobip response for ${correlationId}`);
try {
return await prisma.messageStatus.update({
where: { correlationId },
data: {
status: 'SEND_RESPONSE_INVALID',
statusDescription: 'Infobip response was missing expected messageId.',
updatedAt: new Date(),
},
});
} catch (updateError) {
logger.error(`Error updating status to SEND_RESPONSE_INVALID for ${correlationId}:`, updateError);
return null;
}
}
try {
const updatedMessage = await prisma.messageStatus.update({
where: { correlationId: correlationId },
data: {
infobipMessageId: messageInfo.messageId,
status: messageInfo.status?.name || 'UNKNOWN_POST_SEND',
statusGroup: messageInfo.status?.groupName || 'UNKNOWN',
statusDescription: messageInfo.status?.description || 'Status after sending.',
updatedAt: new Date(),
},
});
logger.info(`Status updated post-send for correlationId ${correlationId} (Infobip ID: ${messageInfo.messageId})`);
return updatedMessage;
} catch (error) {
logger.error(`Error updating message status post-send for ${correlationId}:`, error);
return null;
}
}
async function updateMessageStatusFromWebhook(report) {
const messageId = report.messageId;
if (!messageId) {
logger.warn('Webhook received without messageId:', report);
return null;
}
try {
const existingMessage = await prisma.messageStatus.findFirst({
where: { infobipMessageId: messageId },
});
if (!existingMessage) {
logger.warn(`Webhook received for unknown infobipMessageId: ${messageId}`);
return null;
}
const updatedMessage = await prisma.messageStatus.update({
where: { id: existingMessage.id },
data: {
status: report.status?.name || 'UNKNOWN_WEBHOOK',
statusGroup: report.status?.groupName || 'UNKNOWN',
statusDescription: report.status?.description || 'Status from webhook.',
errorCode: report.error?.id,
errorMessage: report.error?.name,
updatedAt: new Date(report.doneAt || report.sentAt || Date.now()),
},
});
logger.info(`Webhook processed for infobipMessageId ${messageId}. Status: ${updatedMessage.status}`);
return updatedMessage;
} catch (error) {
logger.error(`Error processing webhook for messageId ${messageId}:`, error);
return null;
}
}
module.exports = {
prisma,
saveInitialMessageStatus,
updateMessageStatusPostSend,
updateMessageStatusFromWebhook,
};
3.2 SSE Service (src/services/sseService.js):
This service manages SSE connections and publishes updates.
const SSEChannel = require('sse-channel');
const logger = require('../utils/logger');
const sseChannel = new SSEChannel({
pingInterval: 15000,
historySize: 10,
cors: { origins: ['*'],
headers: ['Cache-Control', 'Connection', 'Content-Type', 'Last-Event-ID']}
});
function initializeSSE(app) {
app.get('/api/messages/sse-status/:correlationId', (req, res) => {
const { correlationId } = req.params;
if (!correlationId) {
return res.status(400).send('Missing correlationId');
}
sseChannel.addClient(req, res, correlationId);
logger.info(`SSE client connected for correlationId: ${correlationId}`);
req.on('close', () => {
logger.info(`SSE client disconnected for correlationId: ${correlationId}`);
});
});
logger.info('SSE service initialized at /api/messages/sse-status/:correlationId');
}
function publishStatusUpdate(correlationId, data) {
if (!correlationId) {
logger.warn('Attempted to publish SSE update without correlationId:', data);
return;
}
sseChannel.publish(
'message_status_update',
data,
{
ids: [correlationId]
}
);
logger.info(`Published SSE update for ${correlationId}: Status - ${data?.status}`);
}
function getClientCount() {
return sseChannel.getConnectionCount();
}
module.exports = {
initializeSSE,
publishStatusUpdate,
getClientCount,
};
3.3 Infobip Service (src/services/infobipService.js):
Handles communication to the Infobip API.
const axios = require('axios');
const config = require('../config');
const logger = require('../utils/logger');
const infobipClient = axios.create({
baseURL: `https://${config.infobip.baseUrl}`,
headers: {
'Authorization': `App ${config.infobip.apiKey}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
async function sendSms(phoneNumber, message, correlationId) {
const url = '/sms/2/text/advanced';
const requestBody = {
messages: [
{
destinations: [{ to: phoneNumber }],
text: message,
notifyUrl: `${config.webhookPublicUrl}/api/messages/webhook`,
notifyContentType: 'application/json',
},
],
};
logger.info(`Sending SMS to ${phoneNumber} with correlationId: ${correlationId}`);
try {
const response = await infobipClient.post(url, requestBody);
logger.info(`Infobip API Response Status: ${response.status}`);
const messageInfo = response.data?.messages?.[0];
if (messageInfo) {
logger.info(`Infobip Message ID: ${messageInfo.messageId}, Status: ${messageInfo.status?.groupName} (${messageInfo.status?.name})`);
} else {
logger.warn('Infobip response structure unexpected:', response.data);
}
return response.data;
} catch (error) {
logger.error(`Error sending SMS via Infobip for ${correlationId}:`);
if (error.response) {
logger.error(`Data: ${JSON.stringify(error.response.data)}`);
logger.error(`Status: ${error.response.status}`);
logger.error(`Headers: ${JSON.stringify(error.response.headers)}`);
throw new Error(`Infobip API error: ${error.response.status} - ${JSON.stringify(error.response.data)}`);
} else if (error.request) {
logger.error('Request Error: No response received from Infobip.', error.request);
throw new Error('Infobip API error: No response received.');
} else {
logger.error('Axios Error:', error.message);
throw new Error(`Infobip API error: ${error.message}`);
}
}
}
module.exports = {
sendSms,
};
4. API Layer: Routes and Controllers
Define the API endpoints and the controller logic that orchestrates the services.
4.1 Define Routes (src/routes/index.js and
src/routes/messageRoutes.js):
const express = require('express');
const messageRoutes = require('./messageRoutes');
const router = express.Router();
router.use('/messages', messageRoutes);
module.exports = router;
const express = require('express');
const messageController = require('../controllers/messageController');
const { validateWebhook } = require('../middleware/webhookValidation');
const router = express.Router();
router.post('/send', messageController.handleSendSms);
router.post('/webhook', validateWebhook, messageController.handleInfobipWebhook);
module.exports = router;
4.2 Implement Controller (src/controllers/messageController.js):
const { v4: uuidv4 } = require('uuid');
const infobipService = require('../services/infobipService');
const dbService = require('../services/databaseService');
const sseService = require('../services/sseService');
const logger = require('../utils/logger');
async function handleSendSms(req, res) {
const { phoneNumber, message } = req.body;
if (!phoneNumber || !message) {
return res.status(400).json({ message: 'Missing required fields: phoneNumber, message' });
}
const correlationId = uuidv4();
try {
await dbService.saveInitialMessageStatus({
correlationId,
phoneNumber,
messageText: message,
});
const infobipResponse = await infobipService.sendSms(phoneNumber, message, correlationId);
const updatedRecord = await dbService.updateMessageStatusPostSend(correlationId, infobipResponse);
res.status(202).json({
message: 'SMS submitted successfully. Waiting for delivery status.',
correlationId: correlationId,
infobipStatus: updatedRecord?.status || 'PENDING_INFOBIP_ID',
infobipMessageId: updatedRecord?.infobipMessageId
});
if(updatedRecord) {
sseService.publishStatusUpdate(correlationId, {
correlationId: updatedRecord.correlationId,
status: updatedRecord.status,
statusGroup: updatedRecord.statusGroup,
description: updatedRecord.statusDescription,
timestamp: updatedRecord.updatedAt,
});
} else {
sseService.publishStatusUpdate(correlationId, {
correlationId: correlationId,
status: 'SEND_RESPONSE_INVALID',
description: 'Failed to get valid confirmation from Infobip after sending.',
timestamp: new Date(),
});
}
} catch (error) {
logger.error(`Failed to process send SMS request for ${correlationId}:`, error.message);
try {
await dbService.prisma.messageStatus.update({
where: { correlationId },
data: { status: 'FAILED_PRE_SEND', errorMessage: error.message, updatedAt: new Date() }
});
} catch (dbError) {
logger.error(`Failed to update DB status after send error for ${correlationId}:`, dbError);
}
sseService.publishStatusUpdate(correlationId, {
correlationId: correlationId,
status: 'FAILED_PRE_SEND',
description: `Failed to initiate SMS send: ${error.message}`,
timestamp: new Date(),
});
res.status(500).json({
message: 'Failed to initiate SMS send.',
correlationId: correlationId,
error: error.message
});
}
}
async function handleInfobipWebhook(req, res) {
const deliveryReports = req.body.results;
if (!Array.isArray(deliveryReports)) {
logger.warn('Webhook received with invalid format (expected ""results"" array):', req.body);
return res.status(400).send('Bad Request: Invalid payload format.');
}
logger.info(`Received webhook with ${deliveryReports.length} report(s).`);
deliveryReports.forEach(async (report) => {
try {
const updatedMessage = await dbService.updateMessageStatusFromWebhook(report);
if (updatedMessage && updatedMessage.correlationId) {
sseService.publishStatusUpdate(updatedMessage.correlationId, {
correlationId: updatedMessage.correlationId,
status: updatedMessage.status,
statusGroup: updatedMessage.statusGroup,
description: updatedMessage.statusDescription,
errorCode: updatedMessage.errorCode,
errorMessage: updatedMessage.errorMessage,
timestamp: updatedMessage.updatedAt,
});
} else {
logger.warn(`Webhook processed but no corresponding record or correlationId found for Infobip Message ID: ${report.messageId}`);
}
} catch (error) {
logger.error(`Error processing individual webhook report for messageId ${report?.messageId}:`, error);
}
});
res.status(200).send('Webhook received.');
}
module.exports = {
handleSendSms,
handleInfobipWebhook,
};
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 β