Bulk SMS

Build a Bulk SMS Broadcast System with Node.js, Express & Infobip API

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.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 4, 2026 β€’ 16 min read

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.

  1. Create Project Directory: Open your terminal and create a new project directory.
   mkdir infobip-bulk-sms
   cd infobip-bulk-sms
  1. Initialize Node.js Project: Initialize npm with default settings using the -y flag.
   npm init -y
  1. 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
  1. 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
  1. Configure nodemon: Add development scripts to package.json.
   {

     "scripts": {
       "start": "node server.js",
       "dev": "nodemon server.js",
       "test": "jest"

     }

   }
  1. 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.

  1. Configure Environment Variables: Create a .env file in the project root. Add this file to .gitignore immediately 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.
  1. Configure .gitignore: Create a .gitignore file 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.

  1. 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:

  1. Import and initialize: Load the Infobip SDK, validate credentials, and create the API client with API Key authentication.
  2. sendBulkSms function: Accepts phone numbers, message text, and optional sender ID. Maps phone numbers to destination objects, constructs the API payload, and sends the request.
  3. Response handling: Returns structured data with bulkId (tracks the entire batch) and individual message statuses.
  4. 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.

  1. 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,
   };
  1. 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;
  1. 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;
  1. 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.

  1. Log in to Infobip: Access your Infobip account dashboard.
  2. Navigate to API Keys: Look for "API Keys," "Developer Tools," or similar in the navigation menu.
  3. Create/View API Key: Create a new API key or view an existing one. Ensure it has permissions for sending SMS messages.
  4. Copy API Key: Securely copy the generated API Key. This is your INFOBIP_API_KEY.
  5. 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 your INFOBIP_BASE_URL.
  6. Update .env: Paste the copied values into your .env file.
   # .env
   # ... other variables
   INFOBIP_BASE_URL="YOUR_COPIED_BASE_URL"
   INFOBIP_API_KEY="YOUR_COPIED_API_KEY"
   # ...
  1. Restart Application: Restart your application to load the new environment variables. nodemon usually 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.

  1. Setup Logger (src/utils/logger.js): This simple console-based logger is suitable for development. For production, use winston or pino for 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;
  1. Centralized Error Handler (src/middleware/errorHandler.js): This middleware catches errors passed via next(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.
  1. Using the Error Handler: In controllers or services, wrap asynchronous operations in try...catch blocks. If an error occurs, call next(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);
   }
  1. Retry Mechanisms: Network issues or temporary Infobip API glitches might occur. Implement retries to improve reliability. Use async-retry for 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 same bulkId, Infobip won't send duplicate messages. To ensure idempotency, generate a unique bulkId (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.

  1. Define Schema (prisma/schema.prisma): Update the schema file to include models for Recipient and Broadcast.

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
   // }
  1. 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
  1. 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;
  1. 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

  1. Install Security Packages:
   npm install helmet express-rate-limit express-validator
  1. Add Helmet for Security Headers (src/app.js):
   const helmet = require('helmet');
   app.use(helmet());
  1. 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);
  1. 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.

  1. Configure Jest (jest.config.js):
   module.exports = {
     testEnvironment: 'node',
     coverageDirectory: 'coverage',
     collectCoverageFrom: ['src/**/*.js'],
     testMatch: ['**/tests/**/*.test.js'],
   };
  1. 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');
     });
   });
  1. 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);
     });
   });
  1. Run Tests:
   npm test

9. Deploying Your SMS Broadcast System

Deploy your application to a cloud platform.

Heroku Deployment

  1. Install Heroku CLI and log in:
   heroku login
  1. Create Heroku app:
   heroku create your-app-name
  1. Add PostgreSQL addon:
   heroku addons:create heroku-postgresql:mini
  1. 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
  1. Add Procfile:
   web: node server.js
   release: npx prisma migrate deploy
  1. Deploy:
   git push heroku main

Docker Deployment

  1. 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"]
  1. 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:
  1. 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 β†’