Developer Quick-Start: Learn how to build a production-ready bulk SMS broadcast system using Node.js, Express, and Infobip API. Complete tutorial with code examples, security best practices, and 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.
Learn how to build a production-ready bulk SMS broadcast system using Node.js, Express, and the Infobip API. This comprehensive guide covers project setup, core functionality, error handling, security, monitoring, and deployment best practices.
By the end of this tutorial, you'll have a functional Express application that sends SMS messages to multiple recipients using Infobip's bulk sending API β perfect for reliably broadcasting alerts, notifications, or marketing messages at scale.
Technologies Used:
- Node.js: JavaScript runtime for server-side applications
- Express: Minimal Node.js web framework
- Infobip: Cloud communications platform with SMS API (via official Node.js SDK)
- dotenv: Secure environment variable management
- Prisma: Next-generation ORM for Node.js and TypeScript
- PostgreSQL: Open-source relational database (MySQL and MariaDB are compatible alternatives with minor code changes)
- Jest & Supertest: Unit and integration testing frameworks
System Architecture:
+-------------+ +-------------------+ +-----------------+ +-------------+
| Client |------>| Node.js/Express |<----->| Infobip Service |------>| Infobip API |
| (Postman/UI)| | API Layer | | (Node.js SDK) | +-------------+
+-------------+ | (Routes, Ctrls) | +-----------------+
+-------------------+
|
V
+-------------------+
| Database (PG) |
| (Prisma ORM) |
+-------------------+
Prerequisites:
- Free or paid Infobip account (sign up here)
- Node.js LTS version (18.x or later recommended) and npm
- PostgreSQL database (version 12 or later, local or cloud-based)
- Basic knowledge of Node.js, Express, REST APIs, and relational databases
- Registered phone number for your Infobip trial account (trial accounts have restrictions: typically 5β10 test numbers, limited sender IDs)
Time to complete: 60β90 minutes | Skill level: Intermediate
1. Setting Up Your Node.js Bulk SMS Project
Initialize your Node.js project, configure the directory structure, and install the required dependencies including the Infobip SDK, Express, and Prisma ORM.
- Create Project Directory: Open your terminal and create a new project directory.
mkdir infobip-bulk-sms
cd infobip-bulk-sms
- Initialize Node.js Project: Initialize npm with default settings using the
-yflag.
npm init -y
- Install Dependencies: Install Express, the Infobip SDK, dotenv, Prisma, and testing tools. These versions are compatible as of January 2025.
npm install express @infobip-api/sdk dotenv pg @prisma/client
npm install --save-dev prisma nodemon jest supertest
- express: Web framework
- @infobip-api/sdk: Official Infobip SDK for Node.js
- dotenv: Loads environment variables from .env
- pg: PostgreSQL client for Node.js (used by Prisma)
- @prisma/client: Prisma's database client
- prisma: Prisma CLI for migrations and studio
- nodemon: Automatically restarts server during development
- jest: Testing framework
- supertest: HTTP assertion library for testing
- Set up Project Structure: Create this directory structure:
infobip-bulk-sms/
βββ prisma/
βββ src/
β βββ controllers/
β βββ routes/
β βββ services/
β βββ utils/
β βββ middleware/
β βββ app.js # Main Express application setup
βββ tests/
β βββ integration/
β βββ unit/
βββ .env # Environment variables (DO NOT COMMIT)
βββ .gitignore
βββ package.json
βββ server.js # Entry point to start the server
- Configure
nodemon: Add development scripts topackage.json.
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "jest"
}
}
- Initialize Prisma: Set up Prisma with PostgreSQL as the provider.
npx prisma init --datasource-provider postgresql
This creates the prisma/ directory (if not already present) and a schema.prisma
file, and updates your .env file with a DATABASE_URL placeholder.
- Configure Environment Variables: Create a
.envfile in the project root. Add this file to.gitignoreimmediately to prevent exposing credentials.
# .env
# Database
DATABASE_URL="postgresql://<user>:<password>@<host>:<port>/<database>?schema=public"
# Infobip Credentials
INFOBIP_BASE_URL="YOUR_INFOBIP_BASE_URL" # Find this in your Infobip account API section
INFOBIP_API_KEY="YOUR_INFOBIP_API_KEY" # Find this in your Infobip account API section
# Application Settings
PORT=3000
NODE_ENV=development # or production
- Replace <...> placeholders in DATABASE\_URL with your PostgreSQL credentials.
- Find your INFOBIP\_BASE\_URL and INFOBIP\_API\_KEY in the Infobip portal: Account Settings β API Keys (format: xxxxx.api.infobip.com for base URL).
- Production note: Use your hosting platform's environment variable system (AWS Secrets Manager, Heroku Config Vars, Kubernetes Secrets) instead of .env files in production for enhanced security.
- Configure
.gitignore: Create a.gitignorefile in the root directory:
# .gitignore
node_modules/
.env
dist/
coverage/
*.log
2. Implementing Infobip SMS Service with Node.js SDK
Encapsulate all Infobip API interactions in a dedicated service module using the official Infobip Node.js SDK. This pattern separates business logic from API integration for better maintainability.
- Create Infobip Service (
src/services/infobipService.js):
const { Infobip, AuthType } = require('@infobip-api/sdk');
const logger = require('../utils/logger');
require('dotenv').config();
if (!process.env.INFOBIP_BASE_URL || !process.env.INFOBIP_API_KEY) {
logger.error('Infobip Base URL or API Key not configured in .env file.');
throw new Error('Infobip credentials missing.');
}
const infobipClient = new Infobip({
baseUrl: process.env.INFOBIP_BASE_URL,
apiKey: process.env.INFOBIP_API_KEY,
authType: AuthType.ApiKey,
});
const sendBulkSms = async (phoneNumbers, messageText, sender = 'InfoSMS') => {
if (!phoneNumbers || phoneNumbers.length === 0) {
throw new Error('Recipient phone numbers array cannot be empty.');
}
if (!messageText) {
throw new Error('Message text cannot be empty.');
}
const destinations = phoneNumbers.map(number => ({ to: number }));
const payload = {
messages: [
{
from: sender,
destinations: destinations,
text: messageText,
},
],
};
try {
logger.info(`Attempting to send bulk SMS to ${phoneNumbers.length} recipients.`);
logger.debug('Infobip Payload:', payload);
const infobipResponse = await infobipClient.channels.sms.send(payload);
const { data } = infobipResponse;
logger.info(`Infobip bulk SMS request successful. Bulk ID: ${data.bulkId}`);
logger.debug('Infobip Response:', data);
return {
bulkId: data.bulkId,
messages: data.messages.map(msg => ({
messageId: msg.messageId,
to: msg.to,
status: msg.status.name,
statusGroup: msg.status.groupName,
})),
};
} catch (error) {
logger.error('Infobip API Error:', error.response ? error.response.data : error.message);
throw new Error(`Failed to send bulk SMS via Infobip: ${error.message}`);
}
};
module.exports = {
sendBulkSms,
};
How it works:
- Import and initialize: Load the Infobip SDK, validate credentials, and create the API client with API Key authentication.
sendBulkSmsfunction: Accepts phone numbers, message text, and optional sender ID. Maps phone numbers to destination objects, constructs the API payload, and sends the request.- Response handling: Returns structured data with bulkId (tracks the entire batch) and individual message statuses.
- Error handling: Catches API errors and throws descriptive exceptions.
3. Building the Express REST API for Bulk SMS
Create Express routes and controllers to expose the bulk SMS sending functionality via a RESTful API endpoint. This layer handles HTTP requests and orchestrates the SMS broadcast workflow.
- Create Broadcast Controller (
src/controllers/broadcastController.js):
const infobipService = require('../services/infobipService');
const prisma = require('../utils/prismaClient');
const logger = require('../utils/logger');
const createBroadcast = async (req, res, next) => {
const { message, recipients, sender } = req.body;
if (!message) {
return res.status(400).json({ error: 'Message content is required.' });
}
let targetRecipients = recipients;
try {
if (!targetRecipients || !Array.isArray(targetRecipients)) {
logger.info('Recipient list not provided in request. Fetching active recipients from DB.');
const activeRecipients = await prisma.recipient.findMany({
where: { isActive: true },
select: { phone: true },
});
if (!activeRecipients || activeRecipients.length === 0) {
return res.status(400).json({ error: 'No recipients provided and no active recipients found in the database.' });
}
targetRecipients = activeRecipients.map(r => r.phone);
logger.info(`Found ${targetRecipients.length} active recipients in DB.`);
}
if (targetRecipients.length === 0) {
return res.status(400).json({ error: 'Recipient list cannot be empty.' });
}
const invalidNumbers = targetRecipients.filter(num => !/^\+?[1-9]\d{1,14}$/.test(num));
if (invalidNumbers.length > 0) {
logger.warn(`Request contains invalid phone numbers: ${invalidNumbers.join(', ')}`);
return res.status(400).json({
error: 'Invalid phone number format detected. Use E.164 format (e.g., +15551234567).',
invalidNumbers: invalidNumbers,
});
}
const result = await infobipService.sendBulkSms(targetRecipients, message, sender);
const broadcastRecord = await prisma.broadcast.create({
data: {
message: message,
status: 'SUBMITTED',
infobipBulkId: result.bulkId,
recipientCount: targetRecipients.length,
}
});
logger.info(`Broadcast record created with ID: ${broadcastRecord.id} and Bulk ID: ${result.bulkId}`);
res.status(202).json({
message: 'Broadcast request accepted successfully.',
broadcastId: broadcastRecord.id,
infobipBulkId: result.bulkId,
submittedMessages: result.messages.length,
});
} catch (error) {
logger.error(`Failed to create broadcast: ${error.message}`);
next(error);
}
};
module.exports = {
createBroadcast,
};
- Create Broadcast Routes (
src/routes/broadcastRoutes.js):
const express = require('express');
const broadcastController = require('../controllers/broadcastController');
const router = express.Router();
router.post('/', broadcastController.createBroadcast);
module.exports = router;
- Set up Express App (
src/app.js):
const express = require('express');
const dotenv = require('dotenv');
const broadcastRoutes = require('./routes/broadcastRoutes');
const logger = require('./utils/logger');
const errorHandler = require('./middleware/errorHandler');
dotenv.config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
});
app.get('/health', (req, res) => res.status(200).json({ status: 'UP' }));
app.use('/api/v1/broadcasts', broadcastRoutes);
app.use((req, res, next) => {
const error = new Error(`Not Found - ${req.originalUrl}`);
res.status(404);
next(error);
});
app.use(errorHandler);
module.exports = app;
- Create Server Entry Point (
server.js):
const app = require('./src/app');
const logger = require('./src/utils/logger');
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
logger.info(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`);
});
process.on('SIGTERM', () => {
logger.info('SIGTERM signal received: closing HTTP server');
server.close(() => {
logger.info('HTTP server closed');
process.exit(0);
});
});
process.on('SIGINT', () => {
logger.info('SIGINT signal received: closing HTTP server');
server.close(() => {
logger.info('HTTP server closed');
process.exit(0);
});
});
process.on('unhandledRejection', (err, promise) => {
logger.error('Unhandled Rejection at:', promise, 'reason:', err);
server.close(() => process.exit(1));
});
API Endpoint Example:
Test the POST /api/v1/broadcasts endpoint using cURL or Postman.
- Method:
POST - URL:
http://localhost:3000/api/v1/broadcasts - Headers:
Content-Type: application/json - Body (JSON):
{
"message": "Hello from our bulk broadcast system! Special offer inside.",
"recipients": ["+15551112222", "+447123456789", "+4915123456789"],
"sender": "MyAppAlerts"
}
- Omit recipients to send to all active recipients in the database (once database is configured).
- cURL Example:
curl -X POST http://localhost:3000/api/v1/broadcasts \
-H "Content-Type: application/json" \
-d '{
"message": "Hello from our bulk broadcast system!",
"recipients": ["+15551112222", "+447123456789"],
"sender": "MyAppAlerts"
}'
- Example Success Response (202 Accepted):
{
"message": "Broadcast request accepted successfully.",
"broadcastId": "clxyzabc1234567890def",
"infobipBulkId": "2034072219640523072",
"submittedMessages": 3
}
- Example Error Response (400 Bad Request):
{
"error": "Invalid phone number format detected. Use E.164 format (e.g., +15551234567).",
"invalidNumbers": [
"12345"
]
}
4. Infobip API Integration: Credentials and Configuration
You already initialized the Infobip client in infobipService.js using environment variables.
Here's how to obtain these credentials.
- Log in to Infobip: Access your Infobip account dashboard.
- Navigate to API Keys: Look for "API Keys," "Developer Tools," or similar in the navigation menu.
- Create/View API Key: Create a new API key or view an existing one. Ensure it has permissions for sending SMS messages.
- Copy API Key: Securely copy the generated API Key. This is your
INFOBIP_API_KEY. - Find Base URL: Your account-specific Base URL is displayed near the API Key or in the API
settings/documentation section. It looks like
xxxxx.api.infobip.com. This is yourINFOBIP_BASE_URL. - Update
.env: Paste the copied values into your.envfile.
# .env
# ... other variables
INFOBIP_BASE_URL="YOUR_COPIED_BASE_URL"
INFOBIP_API_KEY="YOUR_COPIED_API_KEY"
# ...
- Restart Application: Restart your application to load the new environment variables.
nodemonusually handles this automatically.
Security Note: Never commit your .env file or hardcode API keys in source code.
Use environment variables for all sensitive credentials. Rotate API keys regularly β generate new keys every
90 days and revoke old ones immediately.
API Rate Limits: Infobip enforces rate limits based on your account tier. Free tier typically allows 10β20 requests per second. Monitor your usage via the Infobip dashboard and upgrade your plan if needed.
5. Error Handling and Retry Logic for SMS Delivery
Robust error handling and logging are crucial for production systems.
- Setup Logger (
src/utils/logger.js): This simple console-based logger is suitable for development. For production, usewinstonorpinofor advanced features like log levels, file transport, structured logging, and external log aggregation (Datadog, Splunk).
const logger = {
info: (...args) => {
console.log(`[INFO] ${new Date().toISOString()}:`, ...args);
},
warn: (...args) => {
console.warn(`[WARN] ${new Date().toISOString()}:`, ...args);
},
error: (...args) => {
console.error(`[ERROR] ${new Date().toISOString()}:`, ...args);
},
debug: (...args) => {
if (process.env.NODE_ENV === 'development') {
console.debug(`[DEBUG] ${new Date().toISOString()}:`, ...args);
}
},
};
module.exports = logger;
Production Logger Example (winston):
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
),
}),
],
});
module.exports = logger;
- Centralized Error Handler (
src/middleware/errorHandler.js): This middleware catches errors passed vianext(error)and sends a structured response.
const logger = require('../utils/logger');
const errorHandler = (err, req, res, next) => {
logger.error(err.stack);
const statusCode = err.statusCode || res.statusCode || 500;
const finalStatusCode = statusCode < 400 ? 500 : statusCode;
const response = {
message: err.message || 'An unexpected error occurred.',
...(process.env.NODE_ENV !== 'production' && { stack: err.stack }),
...(err.details && { details: err.details }),
};
res.status(finalStatusCode).json(response);
};
module.exports = errorHandler;
- Make sure this middleware is added last in src/app.js, after all routes.
- Using the Error Handler: In controllers or services, wrap asynchronous operations in
try...catchblocks. If an error occurs, callnext(error)to pass it to the centralized handler.
try {
const result = await infobipService.sendBulkSms();
res.status(202).json();
} catch (error) {
logger.error(`Error in createBroadcast: ${error.message}`);
next(error);
}
- Retry Mechanisms: Network issues or temporary Infobip API glitches might occur. Implement
retries to improve reliability. Use
async-retryfor exponential backoff and jitter.
- Install:
npm install async-retry - Example Usage (in
infobipService.js):
const retry = require('async-retry');
const sendBulkSms = async (phoneNumbers, messageText, sender = 'InfoSMS') => {
const destinations = phoneNumbers.map(number => ({ to: number }));
const payload = { messages: [{ from: sender, destinations, text: messageText }] };
return await retry(
async (bail, attemptNumber) => {
logger.info(`Attempt ${attemptNumber} to send bulk SMS via Infobip...`);
try {
const infobipResponse = await infobipClient.channels.sms.send(payload);
const { data } = infobipResponse;
logger.info(`Infobip bulk SMS request successful on attempt ${attemptNumber}. Bulk ID: ${data.bulkId}`);
logger.debug('Infobip Response:', data);
return {
bulkId: data.bulkId,
messages: data.messages.map(msg => ({
messageId: msg.messageId,
to: msg.to,
status: msg.status.name,
statusGroup: msg.status.groupName,
})),
};
} catch (error) {
logger.warn(`Attempt ${attemptNumber} failed: ${error.message}`);
if (error.response) {
const status = error.response.status;
if (status === 401 || status === 400 || status === 403 || status === 404 || status === 422) {
logger.error(`Unrecoverable Infobip API error (${status}). Bailing out.`);
bail(new Error(`Infobip API Error (${status}): ${error.message || 'Client Error'}`));
return;
}
}
throw error;
}
},
{
retries: 3,
factor: 2,
minTimeout: 1000,
maxTimeout: 5000,
randomize: true,
onRetry: (error, attempt) => {
logger.warn(`Retrying Infobip call (attempt ${attempt}) due to error: ${error.message}`);
},
}
);
};
module.exports = { sendBulkSms };
- Idempotency Note: Infobip's API is idempotent when you provide a custom
bulkId. If you retry with the samebulkId, Infobip won't send duplicate messages. To ensure idempotency, generate a uniquebulkId(e.g., using UUID) before the retry loop and include it in the payload.
Circuit Breaker Pattern: For production systems, implement a circuit breaker (using
libraries like opossum) to prevent cascading failures. A circuit breaker stops calling the
Infobip API after repeated failures and retries after a cooldown period.
6. Database Schema with Prisma and PostgreSQL
Use Prisma to define your database schema and interact with the database.
- Define Schema (
prisma/schema.prisma): Update the schema file to include models forRecipientandBroadcast.
Prisma
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Recipient {
id String @id @default(cuid())
phone String @unique // Ensure phone numbers are unique
name String? // Optional recipient name
isActive Boolean @default(true) // Handle opt-outs or inactive users
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Broadcast {
id String @id @default(cuid())
message String
status String // e.g., PENDING, SUBMITTED, PROCESSING, COMPLETED, FAILED
infobipBulkId String? @unique // Store the bulk ID from Infobip
recipientCount Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Optional: Add relation to specific recipients for detailed tracking
// recipients BroadcastRecipient[]
}
// Optional: Join table for many-to-many relationship if tracking per-recipient status
// model BroadcastRecipient {
// id String @id @default(cuid())
// broadcast Broadcast @relation(fields: [broadcastId], references: [id])
// broadcastId String
// recipient Recipient @relation(fields: [recipientId], references: [id])
// recipientId String
// messageId String? // Store individual message ID from Infobip
// status String? // Store individual message status
// submittedAt DateTime @default(now())
// updatedAt DateTime @updatedAt
//
// @@unique([broadcastId, recipientId]) // Ensure a recipient is only listed once per broadcast
// }
- Run Migrations: Generate and apply the migration to create the database tables.
npx prisma migrate dev --name init
This command:
- Creates a migration file in prisma/migrations/
- Applies the migration to your database
- Generates the Prisma Client
- Create Prisma Client Utility (
src/utils/prismaClient.js):
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'info', 'warn', 'error'] : ['error'],
});
module.exports = prisma;
- Seed Database (Optional): Create a seed script to populate test data.
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
async function main() {
await prisma.recipient.createMany({
data: [
{ phone: '+15551112222', name: 'Alice', isActive: true },
{ phone: '+447123456789', name: 'Bob', isActive: true },
{ phone: '+4915123456789', name: 'Charlie', isActive: false },
],
});
console.log('Database seeded successfully');
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
Run the seed script:
node prisma/seed.js
7. Security Best Practices for SMS Broadcasting APIs
Security Middleware
- Install Security Packages:
npm install helmet express-rate-limit express-validator
- Add Helmet for Security Headers (
src/app.js):
const helmet = require('helmet');
app.use(helmet());
- Implement Rate Limiting (
src/middleware/rateLimiter.js):
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Too many requests from this IP, please try again later.',
});
module.exports = limiter;
Apply in src/app.js:
const rateLimiter = require('./middleware/rateLimiter');
app.use('/api/', rateLimiter);
- Add Input Validation (
src/middleware/validators.js):
const { body, validationResult } = require('express-validator');
const validateBroadcastRequest = [
body('message')
.trim()
.notEmpty().withMessage('Message is required')
.isLength({ max: 1600 }).withMessage('Message too long (max 1600 characters)'),
body('recipients')
.optional()
.isArray().withMessage('Recipients must be an array')
.custom((value) => {
if (value && value.length > 1000) {
throw new Error('Maximum 1000 recipients per request');
}
return true;
}),
body('sender')
.optional()
.trim()
.isLength({ max: 11 }).withMessage('Sender ID max 11 characters'),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
},
];
module.exports = { validateBroadcastRequest };
Apply in src/routes/broadcastRoutes.js:
const { validateBroadcastRequest } = require('../middleware/validators');
router.post('/', validateBroadcastRequest, broadcastController.createBroadcast);
Additional Best Practices
- Environment-specific configs: Use different .env files for development, staging, and production
- HTTPS only: Enforce HTTPS in production
- CORS configuration: Configure CORS appropriately for your client applications
- Authentication: Add JWT or OAuth for production API authentication
- Monitoring: Integrate with services like Datadog, New Relic, or Prometheus
- Logging: Use structured logging and external log aggregation
8. Testing Your Bulk SMS Application
Create unit and integration tests for your application.
- Configure Jest (
jest.config.js):
module.exports = {
testEnvironment: 'node',
coverageDirectory: 'coverage',
collectCoverageFrom: ['src/**/*.js'],
testMatch: ['**/tests/**/*.test.js'],
};
- Unit Test Example (
tests/unit/infobipService.test.js):
const infobipService = require('../../src/services/infobipService');
describe('Infobip Service', () => {
test('sendBulkSms throws error when phone numbers array is empty', async () => {
await expect(
infobipService.sendBulkSms([], 'Test message')
).rejects.toThrow('Recipient phone numbers array cannot be empty');
});
test('sendBulkSms throws error when message text is empty', async () => {
await expect(
infobipService.sendBulkSms(['+15551112222'], '')
).rejects.toThrow('Message text cannot be empty');
});
});
- Integration Test Example (
tests/integration/broadcast.test.js):
const request = require('supertest');
const app = require('../../src/app');
describe('POST /api/v1/broadcasts', () => {
test('returns 400 when message is missing', async () => {
const response = await request(app)
.post('/api/v1/broadcasts')
.send({ recipients: ['+15551112222'] });
expect(response.status).toBe(400);
expect(response.body).toHaveProperty('error');
});
test('returns 400 when recipients array is empty', async () => {
const response = await request(app)
.post('/api/v1/broadcasts')
.send({ message: 'Test', recipients: [] });
expect(response.status).toBe(400);
});
});
- Run Tests:
npm test
9. Deploying Your SMS Broadcast System
Deploy your application to a cloud platform.
Heroku Deployment
- Install Heroku CLI and log in:
heroku login
- Create Heroku app:
heroku create your-app-name
- Add PostgreSQL addon:
heroku addons:create heroku-postgresql:mini
- Set environment variables:
heroku config:set INFOBIP_BASE_URL=your_base_url
heroku config:set INFOBIP_API_KEY=your_api_key
heroku config:set NODE_ENV=production
- Add Procfile:
web: node server.js
release: npx prisma migrate deploy
- Deploy:
git push heroku main
Docker Deployment
- Create Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npx prisma generate
EXPOSE 3000
CMD ["node", "server.js"]
- Create docker-compose.yml:
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- DATABASE_URL=postgresql://user:password@db:5432/infobip
- INFOBIP_BASE_URL=${INFOBIP_BASE_URL}
- INFOBIP_API_KEY=${INFOBIP_API_KEY}
depends_on:
- db
db:
image: postgres:14-alpine
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
- POSTGRES_DB=infobip
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
- Build and run:
docker-compose up -d
Conclusion
You now have a production-ready bulk SMS broadcast system with:
- β Express API with proper routing and controllers
- β Infobip SDK integration for bulk SMS sending
- β PostgreSQL database with Prisma ORM
- β Error handling and retry mechanisms
- β Security middleware (Helmet, rate limiting, validation)
- β Structured logging
- β Testing framework
- β Deployment configurations
Next Steps
- Implement webhook handlers for Infobip delivery reports (track message delivery status)
- Add recipient management endpoints (create, update, delete recipients)
- Implement broadcast status retrieval endpoint
- Add job queuing for scheduled broadcasts (using Bull or Agenda)
- Set up monitoring and alerting (using Datadog, New Relic, or Prometheus)
- Implement advanced features (message templates, A/B testing, analytics)
Troubleshooting Common Issues
| Issue | Solution |
|---|---|
Infobip client is not initialized |
Check .env file for correct INFOBIP_BASE_URL and
INFOBIP_API_KEY values |
Invalid phone number format |
Ensure phone numbers use E.164 format (e.g., +15551234567) |
Rate limit exceeded |
Check your Infobip account tier and upgrade if needed, or implement request throttling |
Database connection error |
Verify DATABASE_URL in .env and ensure PostgreSQL is running |
Prisma client not found |
Run npx prisma generate to regenerate the client |
429 Too Many Requests |
Reduce request frequency or upgrade Infobip plan |
401 Unauthorized |
Verify API key is correct and has SMS permissions |
Cost Estimation
Infobip Pricing (approximate as of 2025):
- SMS costs vary by destination country: $0.01β$0.10 per message
- Free tier: 10β20 test messages
- Pay-as-you-go or monthly plans available
- Monitor usage via Infobip dashboard
Infrastructure Costs:
- Heroku: $7/month (Eco Dyno) + $5/month (Mini PostgreSQL) = $12/month
- AWS: ~$15β30/month (t3.micro EC2 + RDS PostgreSQL)
- DigitalOcean: ~$12/month (Basic Droplet + Managed PostgreSQL)
Additional Resources
- Infobip API Documentation
- Infobip Node.js SDK
- Prisma Documentation
- Express Best Practices
- Node.js Security Checklist
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 β