Bulk SMS

Build Node.js Marketing Campaigns with Infobip & Express

A guide to building a Node.js/Express backend for sending SMS via the Infobip API, covering setup, core logic, error handling, and deployment considerations.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 2, 2026 β€’ 13 min read

Developer Quick-Start: A guide to building a Node.js/Express backend for sending SMS via the Infobip API, covering setup, core logic, error handling, and deployment considerations. 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 robust backend system using Node.js and Express to send SMS marketing messages via the Infobip API. We'll cover everything from project setup and core functionality to security, error handling, deployment, and testing, laying a solid foundation for building towards a production-ready application.

By the end of this tutorial, you'll have a functional Express API capable of accepting requests to send targeted SMS messages through Infobip. It covers essential aspects like configuration management, basic error handling, and security considerations, serving as a solid foundation for building more complex marketing automation workflows.

Project Overview and Goals

What We're Building:

We will construct a Node.js application using the Express framework. This application will expose an API endpoint designed to receive requests containing a phone number and a message. Upon receiving a valid request, the application will use the Infobip API to send an SMS message to the specified recipient.

Problem Solved:

This project provides a scalable and maintainable backend solution for businesses needing to integrate SMS marketing or notifications into their workflows. It abstracts the complexities of direct API interaction with Infobip into a simple, reusable service within your Node.js application.

Technologies Used:

  • Node.js: A JavaScript runtime environment for building server-side applications. Chosen for its asynchronous, event-driven nature, making it efficient for I/O operations like API calls.
  • Express: A minimal and flexible Node.js web application framework. Provides a robust set of features for building web APIs quickly and easily.
  • Infobip SMS API: A powerful cloud communication platform API enabling SMS sending globally. Chosen for its reliability, developer-friendly documentation, and feature set.
  • Axios: A popular promise-based HTTP client for Node.js. Used for making requests to the Infobip API. (We chose Axios for this guide to demonstrate direct HTTP interaction and keep dependencies minimal; the official infobip-api-node-sdk is a great alternative for more complex integrations.)
  • dotenv: A zero-dependency module that loads environment variables from a .env file into process.env. Essential for managing sensitive configuration like API keys.

System Architecture:

The basic architecture is straightforward:

+-----------------+      +----------------------+      +----------------+
| Client (e.g.,   |----->| Node.js/Express API  |----->|  Infobip API   |
| Frontend/Admin) |      | (Our Application)    |      | (sms/2/text/..)|
+-----------------+      +----------------------+      +----------------+
      (HTTP Request)          (Validates & Formats)       (Sends SMS)
                                |
                                +-> (Optional: Database for contacts/logs)
  1. A client (like a web frontend, mobile app, or another backend service) sends an HTTP POST request to our Express API endpoint (e.g., /api/campaigns/send-sms).
  2. Our Express application receives the request, validates the input (phone number, message).
  3. The application retrieves necessary credentials (Infobip API Key, Base URL) from environment variables.
  4. It constructs the appropriate request payload for the Infobip SMS API.
  5. Using Axios, it sends the request to the Infobip API endpoint (https://<your-base-url>/sms/2/text/advanced).
  6. Infobip processes the request and sends the SMS message to the recipient's phone.
  7. Infobip returns a response (success or error) to our Express application.
  8. Our application processes Infobip's response and sends an appropriate HTTP response back to the original client.

Prerequisites:

  • Node.js and npm (or yarn) installed on your system.
  • An active Infobip account. If you don't have one, you can sign up for a free trial.
  • Your Infobip API Key and Base URL (details on obtaining these below).
  • Basic understanding of JavaScript, Node.js, Express, and REST APIs.
  • A code editor (like VS Code).
  • A tool for making API requests (like curl or Postman).

1. Setting up the Project

Let's initialize our Node.js project and install the necessary dependencies.

  1. Create Project Directory: Open your terminal or command prompt and create a new directory for your project. Navigate into it.
   mkdir infobip-sms-campaign-api
   cd infobip-sms-campaign-api
  1. Initialize Node.js Project: Run npm init and follow the prompts. You can accept the defaults by pressing Enter repeatedly, or customize as needed. This creates a package.json file.
   npm init -y
  1. Install Dependencies: We need Express for the web server, Axios for HTTP requests, and dotenv for environment variables.
   npm install express axios dotenv
  1. Set up Project Structure: Create the following directories and files for a structured application:
   infobip-sms-campaign-api/
   β”œβ”€β”€ node_modules/
   β”œβ”€β”€ config/
   β”‚   └── index.js        # Centralized configuration
   β”œβ”€β”€ controllers/
   β”‚   └── campaignController.js # Request handling logic
   β”œβ”€β”€ middleware/         # For middleware like error handling, rate limiting
   β”‚   └── errorHandler.js
   β”œβ”€β”€ routes/
   β”‚   └── campaignRoutes.js  # API route definitions
   β”œβ”€β”€ services/
   β”‚   └── infobipService.js  # Infobip API interaction logic
   β”œβ”€β”€ .env                # Environment variables (DO NOT COMMIT)
   β”œβ”€β”€ .env.example        # Example environment variables (Commit this)
   β”œβ”€β”€ .gitignore          # Specifies intentionally untracked files
   β”œβ”€β”€ index.js            # Main application entry point
   └── package.json

You can create these using your file explorer or terminal commands:

   mkdir config controllers middleware routes services
   touch config/index.js controllers/campaignController.js middleware/errorHandler.js routes/campaignRoutes.js services/infobipService.js .env .env.example .gitignore index.js
  1. Configure .gitignore: Prevent sensitive files and unnecessary directories from being committed to version control. Add the following to your .gitignore file:
   # .gitignore

   # Dependencies
   node_modules/

   # Environment variables
   .env

   # Logs
   logs/
   *.log
   npm-debug.log*
   yarn-debug.log*
   yarn-error.log*
   pids/
   *.pid
   *.seed
   *.pid.lock

   # Optional files
   .DS_Store
  1. Set up Environment Variables:
  • Obtain Infobip Credentials:
  1. Log in to your Infobip account.
  2. Navigate to the Homepage or Dashboard.
  3. Your API Key and Base URL should be visible on the main page. The Base URL will look something like xxxxxx.api.infobip.com. Note: Always copy the exact Base URL provided in your Infobip dashboard, as the specific format can vary.
  4. Crucially, ensure you copy both the API Key and the entire Base URL.
  • Create .env.example: Add the following structure to .env.example. This file serves as a template and should be committed.

.env

     # .env.example

     # Server Configuration
     PORT=3000

     # Infobip API Credentials
     INFOBIP_API_KEY=YOUR_INFOBIP_API_KEY_HERE
     INFOBIP_BASE_URL=YOUR_INFOBIP_BASE_URL_HERE #(e.g., xxxxxx.api.infobip.com)
  • Create .env: Create the .env file (which is not committed thanks to .gitignore) and populate it with your actual credentials:

.env

     # .env (DO NOT COMMIT THIS FILE)

     # Server Configuration
     PORT=3000

     # Infobip API Credentials
     INFOBIP_API_KEY=abcdef1234567890abcdef1234567890-abcdef12-abcd-1234-abcd-abcdef123456
     INFOBIP_BASE_URL=1a2b3c.api.infobip.com

Replace the placeholder values with your real key and base URL.

  1. Configure Centralized Settings: Load environment variables securely using dotenv and centralize access.
  • Edit config/index.js:
   require('dotenv').config();

   const config = {
     port: process.env.PORT || 3000,
     infobip: {
       apiKey: process.env.INFOBIP_API_KEY,
       baseUrl: process.env.INFOBIP_BASE_URL,
     },
     nodeEnv: process.env.NODE_ENV || 'development',
   };

   if (!config.infobip.apiKey || !config.infobip.baseUrl) {
     console.error('FATAL ERROR: Infobip API Key or Base URL is not defined in the environment variables.');
     process.exit(1);
   }

   module.exports = config;

Why this approach? Centralizing configuration makes it easier to manage settings and ensures required variables are present at startup. Loading dotenv early makes variables available throughout the application.

  1. Set up the Main Express App: Initialize the Express application and set up basic middleware.
  • Edit index.js:
   const express = require('express');
   const config = require('./config');
   const campaignRoutes = require('./routes/campaignRoutes');
   const errorHandler = require('./middleware/errorHandler');

   const app = express();

   app.use(express.json());

   app.use('/api/campaigns', campaignRoutes);

   app.get('/health', (req, res) => {
     res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() });
   });

   app.use(errorHandler);

   app.listen(config.port, () => {
     console.log(`Server running on port ${config.port} in ${config.nodeEnv} mode`);
     console.log(`Infobip Base URL configured: ${config.infobip.baseUrl}`);
   });

   process.on('unhandledRejection', (reason, promise) => {
     console.error('Unhandled Rejection at:', promise, 'reason:', reason);



   });

   process.on('uncaughtException', (error) => {
     console.error('Uncaught Exception:', error);

     process.exit(1);
   });

   module.exports = app;

Why express.json()? This middleware is crucial for parsing incoming JSON request bodies, which is how we'll receive the phone number and message.

2. Implementing Core Functionality (Sending SMS)

Now, let's implement the logic to interact with the Infobip API. We'll encapsulate this in a dedicated service file.

  1. Create the Infobip Service: This service will handle constructing and sending requests to Infobip.
  • Edit services/infobipService.js:
   const axios = require('axios');
   const config = require('../config');

   const buildUrl = () => {

     const baseUrl = config.infobip.baseUrl.replace(/\/$/, '');
     return `https://${baseUrl}/sms/2/text/advanced`;
   };

   const buildHeaders = () => {
     return {
       'Authorization': `App ${config.infobip.apiKey}`,
       'Content-Type': 'application/json',
       'Accept': 'application/json',
     };
   };

   const buildRequestBody = (destinationNumber, messageText) => {

     if (!destinationNumber || !messageText) {
       throw new Error('Destination number and message text are required.');
     }

     return {
       messages: [
         {
           destinations: [{ to: destinationNumber }],
           text: messageText,


         },
       ],

     };
   };

   const sendSingleSms = async (destinationNumber, messageText) => {
     const url = buildUrl();
     const headers = buildHeaders();
     const requestBody = buildRequestBody(destinationNumber, messageText);

     console.log(`Sending SMS to ${destinationNumber} via Infobip URL: ${url}`);

     try {
       const response = await axios.post(url, requestBody, { headers });
       console.log('Infobip API Success Response:', JSON.stringify(response.data, null, 2));




       if (response.status >= 200 && response.status < 300) {
         return response.data;
       } else {


         throw new Error(`Infobip API request failed with status: ${response.status}`);
       }
     } catch (error) {
       console.error('Infobip API Request Error:', error.message);
       if (error.response) {


         console.error('Error Response Body:', JSON.stringify(error.response.data, null, 2));
         console.error('Error Response Status:', error.response.status);
         console.error('Error Response Headers:', error.response.headers);

         const errorMessage = error.response.data?.requestError?.serviceException?.text || error.message;
         const errorStatus = error.response.status;
         const serviceError = new Error(`Infobip API Error (${errorStatus}): ${errorMessage}`);
         serviceError.status = errorStatus;
         serviceError.infobipError = error.response.data;
         throw serviceError;
       } else if (error.request) {

         console.error('Error Request Data:', error.request);
         throw new Error('Infobip API Error: No response received from server.');
       } else {

         console.error('Error Message:', error.message);
         throw new Error(`Infobip API Setup Error: ${error.message}`);
       }
     }
   };

   module.exports = {
     sendSingleSms,

   };

Why separate service? This follows the principle of Separation of Concerns. The service handles how to talk to Infobip, while controllers (next step) handle what to do with incoming requests and when to call the service. This makes the code modular, testable, and easier to maintain. Why async/await? It provides a cleaner syntax for handling asynchronous operations (like network requests) compared to raw Promises or callbacks.

3. Building the API Layer

Let's define the API route and the controller function that uses our infobipService.

  1. Create the Controller: The controller receives the HTTP request, performs validation, calls the service, and sends the HTTP response.
  • Edit controllers/campaignController.js:
   const infobipService = require('../services/infobipService');

   const sendSms = async (req, res, next) => {
     const { destinationNumber, message } = req.body;



     if (!destinationNumber || typeof destinationNumber !== 'string') {

       const error = new Error(""Missing or invalid 'destinationNumber' parameter (string required)."");
       error.status = 400;
       return next(error);
     }

     if (!/^\+?[1-9]\d{1,14}$/.test(destinationNumber)) {
        const error = new Error(""Invalid phone number format. E.164 format recommended (e.g., +14155552671)."");
        error.status = 400;
        return next(error);
     }
     if (!message || typeof message !== 'string' || message.trim() === '') {
       const error = new Error(""Missing or invalid 'message' parameter (non-empty string required)."");
       error.status = 400;
       return next(error);
     }


     try {
       const result = await infobipService.sendSingleSms(destinationNumber, message);


       const messageStatus = result.messages && result.messages[0] ? result.messages[0].status : null;


       res.status(200).json({
         message: 'SMS submitted successfully to Infobip.',
         infobipResponse: {
           bulkId: result.bulkId,
           messageId: result.messages && result.messages[0] ? result.messages[0].messageId : 'N/A',
           status: messageStatus ? {
               groupId: messageStatus.groupId,
               groupName: messageStatus.groupName,
               id: messageStatus.id,
               name: messageStatus.name,
               description: messageStatus.description,
           } : 'Status N/A',
         }
       });
     } catch (error) {

        console.error(`Error in sendSms controller processing: ${error.message}`);

        next(error);
     }
   };

   module.exports = {
     sendSms,
   };
  1. Define the Route: Connect the API endpoint path to the controller function.
  • Edit routes/campaignRoutes.js:
   const express = require('express');
   const campaignController = require('../controllers/campaignController');

   const router = express.Router();

   router.post('/send-sms', campaignController.sendSms);

   module.exports = router;
  1. Implement Global Error Handler: Ensure the error handler in middleware/errorHandler.js is set up to catch errors passed via next().
  • Edit middleware/errorHandler.js:
   const config = require('../config');

   const errorHandler = (err, req, res, next) => {

     console.error('Error caught by handler:', err.message);
     if (config.nodeEnv !== 'production') {
        console.error(err.stack);
     }
     if (err.infobipError) {
         console.error('Infobip Error Details:', JSON.stringify(err.infobipError, null, 2));
     }

     const statusCode = err.status || 500;
     let message = 'An unexpected error occurred on the server.';


     if (statusCode >= 400 && statusCode < 500) {
         message = err.message || 'Bad Request.';
     }

     else if (config.nodeEnv !== 'production') {
         message = err.message;
     }

     res.status(statusCode).json({
       error: true,
       status: statusCode,
       message: message,
     });
   };

   module.exports = errorHandler;

(Ensure app.use(errorHandler); is present and is the LAST middleware in index.js)

  1. Testing the Endpoint: Start your server:
   node index.js

Open another terminal or use Postman to send a POST request:

  • Using curl: Replace placeholders with your verified phone number (if using a free trial Infobip account) or any target number (if using a paid account) and your message. Use a valid E.164 format number.
     curl -X POST http://localhost:3000/api/campaigns/send-sms \
     -H 'Content-Type: application/json' \
     -d '{
       ""destinationNumber"": ""+14155552671"",
       ""message"": ""Hello from our Node.js Infobip App! Sent on [Date]""
     }'
  • Using Postman:
  1. Set the request type to POST.
  2. Enter the URL: http://localhost:3000/api/campaigns/send-sms
  3. Go to the ""Body"" tab, select ""raw"", and choose ""JSON"" from the dropdown.
  4. Enter the JSON payload:
        {
          ""destinationNumber"": ""+14155552671"",
          ""message"": ""Hello from our Node.js Infobip App via Postman! Sent on [Date]""
        }
  1. Click ""Send"".
  • Expected Success Response (JSON): You should receive a 200 OK status and a JSON body similar to this (IDs and status will vary):
     {
       ""message"": ""SMS submitted successfully to Infobip."",
       ""infobipResponse"": {
         ""bulkId"": ""some-bulk-id-from-infobip"",
         ""messageId"": ""some-message-id-from-infobip"",
         ""status"": {
           ""groupId"": 1,
           ""groupName"": ""PENDING"",
           ""id"": 26,
           ""name"": ""PENDING_ACCEPTED"",
           ""description"": ""Message accepted and pending processing.""
         }
       }
     }

You should also receive the SMS on the target phone shortly after.

  • Example Error Response (JSON): If you provide an invalid phone number format:
     {
         ""error"": true,
         ""status"": 400,
         ""message"": ""Invalid phone number format. E.164 format recommended (e.g., +14155552671).""
     }

If the Infobip API key is wrong (resulting in a 401 from Infobip, caught and returned as 401 by our handler):

     {
         ""error"": true,
         ""status"": 401,
         ""message"": ""Infobip API Error (401): Invalid login details""
     }

4. Integrating with Third-Party Services (Infobip Focus)

This section consolidates the key integration points with Infobip, already touched upon:

  • Configuration:
  • API Key (INFOBIP\_API\_KEY) and Base URL (INFOBIP\_BASE\_URL) are mandatory.
  • Obtained from the Infobip dashboard homepage after login.
  • Stored securely in a .env file (excluded from Git via .gitignore).
  • Loaded at application startup via dotenv and accessed through the config/index.js module.
  • Purpose: INFOBIP\_API\_KEY authenticates your requests. INFOBIP\_BASE\_URL directs requests to your specific Infobip API endpoint cluster.
  • API Interaction:
  • Handled within services/infobipService.js.
  • Uses axios to make HTTP POST requests to https://<INFOBIP\_BASE\_URL>/sms/2/text/advanced.
  • Headers include Authorization: App <INFOBIP\_API\_KEY> and Content-Type: application/json.
  • Request body is structured according to Infobip API specifications for sending messages.
  • Secrets Management:
  • The primary secret is the INFOBIP\_API\_KEY.
  • Using .env locally is standard practice.
  • For production deployment, use the hosting provider's mechanism for setting environment variables securely (e.g., Heroku Config Vars, AWS Secrets Manager, Docker secrets). Never commit .env files containing production keys.
  • Fallback Mechanisms (Conceptual):
  • Retries: For transient network errors or specific Infobip error codes (like temporary throttling), implement a retry strategy (see Section 5).
  • Queuing: For extended Infobip outages or high-volume sending, consider using a message queue (e.g., RabbitMQ, Redis Queue, AWS SQS). Your API endpoint would add the message job to the queue, and a separate worker process would consume jobs from the queue and attempt to send via Infobip. This decouples the API response from the actual sending attempt, improving responsiveness and resilience. (Implementation of queuing is beyond this basic guide).

5. Error Handling, Logging, and Retry Mechanisms

Production applications require robust error handling and logging.

  1. Consistent Error Handling Strategy:
  • Service Layer: The infobipService.js catches errors from the axios request. It logs detailed error information (status code, response body) to the console (or a proper logger). It then throws a new, potentially enriched error (attaching status code, etc.) upwards.
  • Controller Layer: The campaignController.js uses a try...catch block. Validation errors are passed to next(error). Errors from the service layer are caught and also passed to next(error).
  • Global Error Handler: The middleware/errorHandler.js (created in Step 3.3) acts as a centralized place to catch all errors passed via next(). It logs the error and sends a consistently formatted, user-friendly JSON response to the client, avoiding leakage of sensitive internal details in production.
  1. Logging:
  • Current: Using console.log and console.error. Sufficient for basic development.
  • Production: Implement a structured logger like winston or pino.
  • Configure different log levels (debug, info, warn, error).
  • Output logs to files or log management services (e.g., Datadog, Logstash, CloudWatch).
  • Include contextual information (timestamps, request IDs, user info if applicable).
  • Log in JSON format for easier parsing by log aggregation tools.

Example using Winston (conceptual setup):

   npm install winston
   const winston = require('winston');
   const config = require('./config');

   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()
     ),
     defaultMeta: { service: 'infobip-sms-api' },
     transports: [

       new winston.transports.File({ filename: 'error.log', level: 'error' }),

       new winston.transports.File({ filename: 'combined.log' }),
     ],
   });

   if (config.nodeEnv !== 'production') {
     logger.add(new winston.transports.Console({
       format: winston.format.combine(
          winston.format.colorize(),
          winston.format.simple()
       ),
     }));
   }

   module.exports = logger;
  1. Retry Mechanisms: Network issues or temporary service unavailability can cause API calls to fail. Implement retries with exponential backoff.
  • Using axios-retry (Recommended): A simple way to add retry logic to Axios requests.
     npm install axios-retry

Modify services/infobipService.js:

     const axios = require('axios');
     const axiosRetry = require('axios-retry').default;
     const config = require('../config');

     const infobipAxiosInstance = axios.create();

     axiosRetry(infobipAxiosInstance, {
       retries: 3,
       retryDelay: (retryCount, error) => {

         console.warn(`Retry attempt ${retryCount} for ${error.config.url} due to ${error.message}`);
         return retryCount * 1000;
       },
       retryCondition: (error) => {


         const shouldRetry = axiosRetry.isNetworkOrIdempotentRequestError(error) ||
                            (error.response && error.response.status >= 500);
         if (!shouldRetry && error.response) {

             console.error(`Not retrying request due to status ${error.response.status}`);
         }
         return shouldRetry;
       },
       shouldResetTimeout: true,
     });

     const sendSingleSms = async (destinationNumber, messageText) => {
       const url = buildUrl();
       const headers = buildHeaders();
       const requestBody = buildRequestBody(destinationNumber, messageText);


       console.log(`Sending SMS to ${destinationNumber} via Infobip URL: ${url}`);

       try {

         const response = await infobipAxiosInstance.post(url, requestBody, { headers });

         console.log('Infobip API Success Response:', JSON.stringify(response.data, null, 2));

         if (response.status >= 200 && response.status < 300) {
           return response.data;
         } else {
           throw new Error(`Infobip API request failed with status: ${response.status}`);
         }
       } catch (error) {

         console.error('Infobip API Request Error:', error.message);
         if (error.response) {


           console.error('Error Response Body:', JSON.stringify(error.response.data, null, 2));
           console.error('Error Response Status:', error.response.status);
           console.error('Error Response Headers:', error.response.headers);

           const errorMessage = error.response.data?.requestError?.serviceException?.text || error.message;
           const errorStatus = error.response.status;
           const serviceError = new Error(`Infobip API Error (${errorStatus}): ${errorMessage}`);
           serviceError.status = errorStatus;
           serviceError.infobipError = error.response.data;
           throw serviceError;
         } else if (error.request) {

           console.error('Error Request Data:', error.request);
           throw new Error('Infobip API Error: No response received from server.');
         } else {

           console.error('Error Message:', error.message);
           throw new Error(`Infobip API Setup Error: ${error.message}`);
         }
       }
     };

     module.exports = {
       sendSingleSms,

     };

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 β†’