Developer Quick-Start: Learn how to build a production-ready bulk SMS broadcast system using Node.js, Express.js, and Infobip API. Step-by-step tutorial with code examples, error handling, and database integration. 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.
Learn how to build a production-ready bulk SMS broadcast system using Node.js and Express.js with the Infobip API. This comprehensive tutorial covers everything from initial project setup to deploying a scalable SMS messaging service with error handling, database integration, and security best practices.
This guide provides a step-by-step walkthrough for implementing bulk SMS messaging functionality. By the end, you'll have a fully functional Express API endpoint capable of sending SMS messages to multiple recipients simultaneously using Infobip's Node.js SDK.
What You'll Build: Node.js Bulk SMS Service Overview
This guide provides a comprehensive, step-by-step walkthrough for building a production-ready Node.js application using the Express framework to send bulk broadcast SMS messages via the Infobip API. We will cover project setup, core implementation, API design, error handling, security, deployment, and verification.
By the end of this guide, you will have a functional Express API endpoint capable of receiving a list of phone numbers and a message, then efficiently dispatching that message to all recipients using Infobip's robust communication platform.
Project Overview and Goals
What We're Building:
We are creating a backend service built with Node.js and Express. This service will expose a single API
endpoint (/api/broadcast) that accepts a POST request containing:
- A list of recipient phone numbers.
- The text message content to be sent.
The service will then use the Infobip Node.js SDK to send the specified message to all phone numbers in the list via SMS.
Problem Solved:
This addresses the common need for applications to send notifications, alerts, marketing messages, or other communications to multiple users simultaneously via SMS, leveraging a reliable third-party provider like Infobip for delivery.
Technologies Used:
- Node.js: A JavaScript runtime environment for building server-side applications. Chosen for its asynchronous, event-driven nature, suitable for I/O-heavy tasks like API interactions.
- Express.js: A minimal and flexible Node.js web application framework. Chosen for its simplicity, widespread adoption, and ease of building RESTful APIs.
- Infobip API & Node.js SDK (
@infobip-api/sdk): Infobip provides communication APIs (SMS, WhatsApp, etc.). We use their official Node.js SDK for cleaner integration compared to manual HTTP requests. - dotenv: A module to load environment variables from a .env file into process.env, essential for managing sensitive credentials securely during local development.
- (Optional) Prisma & SQLite: For demonstrating database interaction (logging results), though not strictly required for the core broadcast function.
- (Optional) express-rate-limit: Middleware for basic rate limiting to protect the API endpoint.
System Architecture:
graph LR
A[Client (e.g., Web/Mobile App)] --> B{Node.js Express API<br>(POST /api/broadcast)<br>- Validate Request<br>- Use Infobip SDK<br>- (Optional) Log to DB<br>- Return Response};
B --> C[Infobip API<br>(SMS Sending)];
B -.-> D[(Optional) Database<br>(e.g., SQLite/Postgres)];
style D fill:#eee,stroke:#ccc,stroke-dasharray: 5 5
Prerequisites:
- Node.js and npm/yarn: Node.js v22 (Jod, Active LTS) or v20 (Iron, Maintenance LTS) recommended for production use. The @infobip-api/sdk requires Node.js 14 minimum. Check your version with node -v.
- Infobip Account: A registered account on Infobip.
- Infobip API Credentials: API Key and Base URL from your Infobip account dashboard. Note: Trial accounts can typically only send SMS to the registered phone number.
- Basic Terminal/Command Line Knowledge: Familiarity with navigating directories and running commands.
- Text Editor or IDE: Like VS Code, WebStorm, etc.
1. Node.js Project Setup and Dependencies
Let's initialize our Node.js project and install the necessary dependencies.
- Create Project Directory: Open your terminal and create a new directory for the project, then navigate into it.
mkdir infobip-bulk-sms-express
cd infobip-bulk-sms-express
- Initialize Node.js Project: This creates a
package.jsonfile to manage project details and dependencies.
npm init -y
yarn init -y
(The -y flag accepts default settings; you can omit it to customize project details).
- Install Dependencies: We need Express for the web server, the Infobip SDK for SMS
sending, and
dotenvfor environment variable management.
npm install express @infobip-api/sdk dotenv
yarn add express @infobip-api/sdk dotenv
- Install Development Dependencies (Optional but Recommended):
nodemonautomatically restarts the server on file changes, speeding up development.
npm install --save-dev nodemon
yarn add --dev nodemon
- Create Project Structure: Organize the code logically.
mkdir src
mkdir src/routes
mkdir src/controllers
mkdir src/services
mkdir src/config
touch src/server.js
touch src/routes/broadcastRoutes.js
touch src/controllers/broadcastController.js
touch src/services/infobipService.js
touch src/config/infobipClient.js
touch .env
touch .gitignore
- Configure
.gitignore: Prevent committing sensitive files and unnecessary directories.
# .gitignore
# Dependencies
node_modules/
# Environment variables (IMPORTANT!)
.env*
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Build output
dist/
build/
# OS generated files
.DS_Store
Thumbs.db
# Database files (example for SQLite)
*.db
*.db-journal
- Set up
.envFile: Store sensitive credentials here for local development only. Never commit this file to version control. See Deployment section for production handling.
.env
# .env
# Infobip Credentials (Replace with your actual values from Infobip Dashboard)
INFOBIP_API_KEY=YOUR_INFOBIP_API_KEY_HERE
INFOBIP_BASE_URL=YOUR_INFOBIP_BASE_URL_HERE
# Application Settings
PORT=3000
# Database URL (if using Prisma with SQLite example)
# DATABASE_URL="file:./dev.db"
- Replace placeholders with your actual Infobip API Key and Base URL found in your Infobip dashboard. The Base URL looks something like xxxxx.api.infobip.com.
- Add
startanddevScripts topackage.json: These scripts make running the application easier. Openpackage.jsonand ensure thescriptssection looks like this:
"scripts": {
"start": "node src/server.js",
"dev": "nodemon src/server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
2. Implementing Core SMS Functionality with Infobip SDK
We'll encapsulate the Infobip interaction logic within a dedicated service module.
- Configure Infobip Client: Create a reusable Infobip client instance.
import { Infobip, AuthType } from '@infobip-api/sdk';
import dotenv from 'dotenv';
dotenv.config();
const apiKey = process.env.INFOBIP_API_KEY;
const baseUrl = process.env.INFOBIP_BASE_URL;
if (!apiKey || !baseUrl) {
console.error('Error: INFOBIP_API_KEY and INFOBIP_BASE_URL must be set in environment variables.');
process.exit(1);
}
const infobipClient = new Infobip({
baseUrl: baseUrl,
apiKey: apiKey,
authType: AuthType.ApiKey,
});
export default infobipClient;
- Why: We centralize the client creation. dotenv.config() loads variables from .env (useful locally). We add checks to ensure critical variables are present. AuthType.ApiKey explicitly tells the SDK how to authenticate.
- Create the Infobip Service: This service will contain the function to send bulk SMS messages.
import infobipClient from '../config/infobipClient.js';
const sendBulkSms = async (recipients, messageText, sender = 'InfoSMS') => {
if (!recipients || recipients.length === 0) {
throw new Error('Recipients array cannot be empty.');
}
if (!messageText) {
throw new Error('Message text cannot be empty.');
}
const destinations = recipients.map(number => ({ to: number }));
try {
console.log(`Attempting to send SMS via Infobip to ${recipients.length} recipients...`);
const response = await infobipClient.channels.sms.send({
messages: [
{
from: sender,
destinations: destinations,
text: messageText,
},
],
});
console.log('Infobip API Response Data:', JSON.stringify(response.data, null, 2));
return response.data;
} catch (error) {
console.error('Error sending SMS via Infobip:', error.response ? JSON.stringify(error.response.data, null, 2) : error.message);
const errorMessage = error.response?.data?.requestError?.serviceException?.text || error.message || 'Unknown Infobip API error';
throw new Error(`Infobip API error: ${errorMessage}`);
}
};
export { sendBulkSms };
- Why: This encapsulates the logic. We validate inputs (recipients, messageText). We map the simple array of numbers to the destinations array format expected by the SDK ([{ to: 'number1' }, { to: 'number2' }]). The core logic is the infobipClient.channels.sms.send call. We structure the payload with one messages object containing multiple destinations for efficient broadcast. Error handling logs detailed information from the API response if available. A comment advises on more concise production logging.
3. Building the Express API Endpoint for Bulk SMS
Now, let's create the Express endpoint that will use our infobipService.
- Create the Controller: Handles incoming requests, validates input, calls the service, and sends the response.
import { sendBulkSms } from '../services/infobipService.js';
const handleBroadcastRequest = async (req, res) => {
const { recipients, message, sender } = req.body;
if (!recipients || !Array.isArray(recipients) || recipients.length === 0) {
return res.status(400).json({
success: false,
message: 'Invalid input: "recipients" must be a non-empty array of phone numbers.',
});
}
if (!message || typeof message !== 'string' || message.trim() === '') {
return res.status(400).json({
success: false,
message: 'Invalid input: "message" must be a non-empty string.',
});
}
const invalidNumbers = recipients.filter(num => typeof num !== 'string' || !/^\+?\d{7,15}$/.test(num.replace(/\s/g, '')));
if (invalidNumbers.length > 0) {
return res.status(400).json({
success: false,
message: `Invalid phone number format detected for: ${invalidNumbers.join(', ')}. Use international format (e.g., +15551234567).`,
invalidRecipients: invalidNumbers
});
}
try {
console.log(`Processing broadcast request for ${recipients.length} recipients, sender: ${sender || 'default (InfoSMS)'}`);
const result = await sendBulkSms(recipients, message, sender);
res.status(200).json({
success: true,
message: `SMS broadcast request accepted by Infobip for ${recipients.length} recipients.`,
infobipResponse: result,
});
} catch (error) {
console.error('Broadcast request processing failed:', error.message);
res.status(500).json({
success: false,
message: 'Failed to process broadcast SMS request.',
error: error.message,
});
}
};
export { handleBroadcastRequest };
- Why: Separates request handling logic from the core service logic. Implements essential input validation to prevent invalid data from reaching the service/API. Provides clear success and error responses in JSON format. Passes control to the infobipService.
- Create the Route: Defines the API endpoint path and connects it to the controller.
import express from 'express';
import { handleBroadcastRequest } from '../controllers/broadcastController.js';
const router = express.Router();
router.post('/broadcast', handleBroadcastRequest);
export default router;
- Why: Maps the HTTP method (POST) and path (/api/broadcast) to the specific controller function. Keeps routing definitions clean and separate.
- Set up the Main Server File: Integrates all parts: loads environment variables, configures Express middleware, mounts the router, and starts the server.
import express from 'express';
import dotenv from 'dotenv';
import broadcastRoutes from './routes/broadcastRoutes.js';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json({ limit: '1mb' }));
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.originalUrl} [${req.ip}]`);
next();
});
app.use('/api', broadcastRoutes);
app.get('/health', (req, res) => {
res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() });
});
app.use((err, req, res, next) => {
console.error('Unhandled Error:', err.stack || err);
res.status(err.status || 500).json({
success: false,
message: err.message || 'An unexpected internal server error occurred.',
error: process.env.NODE_ENV === 'development' ? err.stack : undefined,
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`Configured Infobip Base URL: ${process.env.INFOBIP_BASE_URL}`);
});
- Why: This is the application's entry point. express.json() is crucial for parsing the request body. Rate limiting and Helmet (commented out) are vital security measures. Basic logging helps track requests. Mounting the routes under /api namespaces the API. A health check is standard practice. A global error handler provides a fallback for unexpected issues.
4. Configuring Infobip API Integration
This section reinforces the Infobip-specific configuration steps.
- Obtaining Credentials:
- Log in to your Infobip Customer Portal.
- Navigate to the Homepage or look for sections like API Keys Management or Developer Tools (UI may vary). You might find your Base URL on the homepage under API access details.
- Generate or find your API Key. Treat this like a password β keep it secret and secure.
- Note your specific Base URL (e.g., xyz123.api.infobip.com). This is unique to your account or region.
- Secure Storage (
.envfor Local Dev):
- As done in Step 1.7, place your INFOBIP\_API\_KEY and INFOBIP\_BASE\_URL in the .env file at the project root for local development only.
- Crucially: Ensure .env (and variants like .env.local) is listed in your .gitignore file to prevent
accidental commits. Do not deploy
.envfiles to production. Use platform environment variables instead (see Section 12).
- Loading Credentials:
- The dotenv.config() call at the top of src/config/infobipClient.js (and potentially src/server.js if needed early) loads these variables into process.env when running locally. In deployed environments, process.env will be populated by the platform.
- SDK Initialization (
src/config/infobipClient.js):
- The Infobip class is instantiated with the baseUrl, apiKey, and authType: AuthType.ApiKey. This configures the shared client instance used by infobipService.js.
- Environment Variables Explained:
- INFOBIP\_API\_KEY: (String) Your secret key for authenticating requests with the Infobip API. Format: Typically a long alphanumeric string. Obtain from Infobip dashboard. Treat as highly sensitive.
- INFOBIP\_BASE\_URL: (String) The specific domain assigned to your Infobip account for API requests. Format: subdomain.api.infobip.com. Obtain from Infobip dashboard.
- PORT: (Number) The network port your Express server will listen on. Format: Integer (e.g., 3000, 8080). Set according to your environment needs or platform requirements.
- NODE\_ENV: (String) Typically set to production in deployed environments, development locally. Used by Express and other libraries to optimize behavior (e.g., caching, error details).
5. Error Handling and Logging Best Practices
Production systems need robust error handling and logging.
- Consistent Error Strategy:
- Validation Errors (Controller): Return 400 Bad Request with clear JSON messages indicating the specific input issue (as shown in broadcastController.js).
- Service Errors (Infobip API): The infobipService.js catches errors from the SDK. It logs the detailed error (often including Infobip's specific error message) and throws a new, more general error. The controller catches this and returns 500 Internal Server Error (or potentially other 4xx/5xx codes if more specific error types were identified and mapped).
- Unhandled Errors (Server): The global error handler in server.js catches anything missed (e.g., errors in middleware, unhandled promise rejections if not using modern Node/Express error handling), logs it, and returns a generic 500 error message to avoid leaking implementation details.
- Logging:
- Basic Console Logging: We use console.log for request tracing and info, and console.error for errors. Suitable for development, but limited in production.
- Structured Logging (Recommended for Production): Use libraries like Winston or Pino. They provide:
- Log Levels: (e.g., error, warn, info, debug) to control verbosity and filter logs.
- JSON Formatting: Makes logs machine-readable for parsing by log aggregation tools (like ELK stack, Datadog, Splunk, Loki).
- Transports: Output logs to files, standard output/error, databases, or external logging services.
- Context: Easily add request IDs, user info (if applicable), etc., to logs for better tracing.
- Example (Conceptual with Pino):
import pino from 'pino';
const logger = pino({ level: process.env.LOG_LEVEL || 'info' });
logger.info({ requestId: req.id }, 'Broadcast request received...');
logger.error({ err: error, requestId: req.id }, 'Infobip API error');
- Retry Mechanisms:
- Infobip Internal: Infobip likely handles some transient network issues internally when submitting SMS.
- Application-Level (Use with Caution): For critical broadcasts, you might implement retries in your service for specific, potentially temporary Infobip errors (e.g., 429 Too Many Requests, 5xx server errors).
- Strategy: Use libraries like async-retry or p-retry. Implement exponential backoff (wait progressively longer between attempts: 1s, 2s, 4s...) with jitter (randomness) to avoid thundering herd issues. Limit the number of retries.
- Caveat: Retrying API calls that initiate actions (like sending SMS) requires careful consideration of idempotency. Infobip's API might support idempotency keys, or you need to ensure your logic doesn't cause duplicate sends if a request succeeds but the response is lost. For simple broadcast submission, relying on the initial 2xx acceptance and monitoring via Delivery Reports (Section 10) might be safer and simpler than complex client-side retry logic.
- Testing Error Scenarios:
- Send requests with missing/invalid recipients or message.
- Send requests with incorrectly formatted phone numbers.
- Temporarily use an invalid INFOBIP\_API\_KEY in environment variables to trigger authentication errors.
- (If possible) Send to a known blocklisted or invalid number format that Infobip might reject immediately.
- Simulate network errors by temporarily blocking access to the Infobip Base URL.
- Use tools like Postman or curl (see Section 13) to manually trigger these conditions.
6. Database Integration with Prisma ORM (Optional)
While not essential for the core broadcast function, logging results to a database provides auditability and tracking. We'll use Prisma ORM with SQLite for this example.
- Install Prisma:
npm install --save-dev prisma
npm install @prisma/client
yarn add --dev prisma
yarn add @prisma/client
- Initialize Prisma:
npx prisma init --datasource-provider sqlite
- Creates prisma/schema.prisma and updates .env with DATABASE\_URL=""file:./dev.db"". Ensure dev.db is in .gitignore.
- Define Schema (
prisma/schema.prisma): Model the broadcast jobs and their individual message results.
Prisma
// prisma/schema.prisma
generator client {
provider = ""prisma-client-js""
}
datasource db {
provider = ""sqlite"" // Using SQLite for simplicity
url = env(""DATABASE_URL"") // Loads from .env
}
// Model for a high-level broadcast job request
model BroadcastJob {
id String @id @default(cuid()) // Unique job ID (e.g., CUID)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
message String // The message text sent
sender String? // The sender ID used (e.g., 'InfoSMS', phone number)
status String // Overall status: PENDING, ACCEPTED, FAILED_SUBMISSION
infobipBulkId String? @unique // The Bulk ID from Infobip, if accepted
recipientCount Int // How many recipients were targeted initially
errorMessage String? // Error message if the job failed submission to Infobip
// Relation to individual message results (one-to-many)
// Tracks the status of each message within the job
results MessageResult[]
@@index([createdAt])
@@index([status])
}
// Model for individual message results within a job
model MessageResult {
id String @id @default(cuid())
jobId String // Foreign key linking back to BroadcastJob
job BroadcastJob @relation(fields: [jobId], references: [id], onDelete: Cascade) // Link back to the job
recipient String // The recipient phone number
submittedAt DateTime @default(now())
infobipMessageId String? @unique // Infobip message ID for this specific message
initialStatus String // Initial status from Infobip (e.g., ""PENDING_ACCEPTED"", ""REJECTED_DESTINATION"")
initialStatusGroup String? // e.g., ""PENDING"", ""REJECTED"", ""DELIVERED"" (group name)
initialErrorCode Int? // Potential error code from Infobip status object
// Fields to potentially update via Delivery Reports webhook
finalStatus String? // Final delivery status (e.g., ""DELIVERED_TO_HANDSET"", ""FAILED_UNDELIVERABLE"")
finalizedAt DateTime? // Timestamp when final status was received
@@index([jobId])
@@index([recipient])
@@index([infobipMessageId])
@@index([finalStatus])
}
- ERD: BroadcastJob (1) -> (\*) MessageResult. Added indexes for common query fields. Added onDelete: Cascade so deleting a job removes its results.
- Apply Migrations: Create the database file (
dev.db) and apply the schema changes.
npx prisma migrate dev --name init-broadcast-schema
- Generates SQL migration files in prisma/migrations and updates the database.
- Create Prisma Client Instance: A reusable client instance.
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient({
});
export default prisma;
- Update Controller to Log Data: Modify
handleBroadcastRequestto interact with the database.
import { sendBulkSms } from '../services/infobipService.js';
import prisma from '../db/prismaClient.js';
const handleBroadcastRequest = async (req, res) => {
const { recipients, message, sender } = req.body;
if (!recipients || !Array.isArray(recipients) || recipients.length === 0 ) {
}
let jobRecord;
try {
jobRecord = await prisma.broadcastJob.create({
data: {
message: message,
sender: sender || 'InfoSMS',
status: 'PENDING',
recipientCount: recipients.length,
},
});
console.log(`Created initial BroadcastJob record ID: ${jobRecord.id}`);
console.log(`Processing broadcast request JobID ${jobRecord.id} for ${recipients.length} recipients...`);
const infobipResult = await sendBulkSms(recipients, message, sender);
await prisma.broadcastJob.update({
where: { id: jobRecord.id },
data: {
status: 'ACCEPTED',
infobipBulkId: infobipResult.bulkId,
results: {
create: infobipResult.messages.map(msg => ({
recipient: msg.to,
infobipMessageId: msg.messageId,
initialStatus: msg.status.name,
initialStatusGroup: msg.status.groupName,
initialErrorCode: msg.status.id,
})),
},
updatedAt: new Date(),
},
});
console.log(`Successfully submitted JobID ${jobRecord.id} to Infobip. Bulk ID: ${infobipResult.bulkId}`);
res.status(200).json({
success: true,
message: `SMS broadcast request accepted by Infobip for ${recipients.length} recipients.`,
jobId: jobRecord.id,
infobipResponse: infobipResult,
});
} catch (error) {
console.error(`Broadcast request processing failed for JobID ${jobRecord?.id || 'N/A'}:`, error.message);
if (jobRecord) {
try {
await prisma.broadcastJob.update({
where: { id: jobRecord.id },
data: {
status: 'FAILED_SUBMISSION',
errorMessage: error.message,
updatedAt: new Date(),
},
});
console.log(`Updated JobID ${jobRecord.id} status to FAILED_SUBMISSION.`);
} catch (dbError) {
console.error(`Failed to update job record ${jobRecord.id} after Infobip error:`, dbError);
}
}
res.status(500).json({
success: false,
message: 'Failed to process broadcast SMS request.',
jobId: jobRecord?.id,
error: error.message,
});
}
};
export { handleBroadcastRequest };
- Why: Adds database logging around the Infobip call. Creates a BroadcastJob record before calling Infobip, updates it with the bulkId and individual message statuses on success, or updates it with an error status on failure. This provides a persistent record of each attempt and its outcome. Includes basic error handling for the database update itself.
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 β