Frequently Asked Questions
Input validation prevents sending messages to invalid numbers, exceeding character limits, or passing malicious data to the Infobip API. It improves security and reliability.
Use the Infobip SMS API's /sms/2/text/advanced
endpoint. Make a POST request to this endpoint with the necessary authorization and request body containing recipient number, message text, and optionally, the sender ID.
Express.js acts as the web framework for the Node.js application. It handles routing, middleware (like authentication), and HTTP request/response management. It simplifies building robust and scalable web APIs for sending SMS.
US regulations require Application-to-Person (A2P) 10DLC messages to be sent under registered campaigns. Registering a brand and campaign with Infobip ensures compliance, preventing message filtering and failure.
Use a custom sender ID only if it's registered and compliant with regulations for your target region. If unsure, rely on Infobip's default configured sender ID to avoid delivery issues.
Install Winston (npm install winston
) and configure a logger instance. Use logger.
(e.g., logger.info
, logger.error
) to replace console.
. Set up transports for different environments (console, file, external services).
The .env
file stores sensitive configuration data, such as your Infobip API key, base URL, and any internal API keys for your application. It is crucial for security to never commit the .env
file to version control.
Implement comprehensive error handling at each level: service, controller, and global handlers. Log detailed errors server-side using Winston but provide generic error messages to clients. Use Axios interceptors or dedicated retry libraries for handling transient network issues.
The project uses Node.js with Express, Axios for making API requests, dotenv for environment variables, Winston for logging, and the Infobip API for sending SMS messages.
Create a project directory, initialize npm (npm init -y
), install required packages (npm install express axios dotenv winston
), structure your project (routes, services, controllers), and configure your .env
file with credentials.
Implement retries for transient errors like network issues or 5xx server errors from Infobip. Use libraries like async-retry
or axios-retry
. Never retry on client errors (4xx) like validation failures.
Organize code into modules with distinct responsibilities: routes for defining API endpoints, controllers for handling requests, services for interacting with external APIs (like Infobip), and middleware for cross-cutting concerns.
The recommended structure includes src/
for source code, containing folders for routes, services, controllers, config, and middleware. The server.js
file serves as the main entry point.
Yes, but free trials usually limit sending to the phone number verified during signup. Check Infobip's free trial terms for limitations.
Send SMS with Infobip API in Node.js: Complete Express Integration Guide
Build a robust Node.js application using Express to send SMS messages via the Infobip API for marketing campaigns. This step-by-step tutorial covers API authentication, 10DLC compliance, error handling, and production-ready logging with Winston.
You'll create a backend service that accepts requests to send targeted SMS messages, integrates securely with Infobip, handles errors gracefully, and follows production-ready best practices.
What you'll build:
Technology Stack:
System Architecture:
Prerequisites:
Final Outcome:
You'll have a functional Express application with a secured API endpoint (
/api/campaign/send-sms
) that:Configuration uses environment variables for security.
1. Node.js Project Setup for Infobip SMS Integration
Initialize the Node.js project and install dependencies.
Create Project Directory: Create a new directory and navigate into it:
Initialize npm: Initialize the project (accept defaults or customize):
Install Dependencies: Install Express, Axios, dotenv, and Winston:
Create Project Structure: Set up the directory structure:
Directory structure:
src/
: All source codesrc/routes/
: Express route definitionssrc/services/
: External service interaction logic (Infobip)src/controllers/
: Request handlerssrc/config/
: Configuration files (logger)src/middleware/
: Custom middleware (authentication)src/server.js
: Main application entry point.env
: Environment variables (Never commit to Git).gitignore
: Files Git should ignoreConfigure
.gitignore
: Add these entries to prevent committing sensitive files:Set up Environment Variables: Add placeholders to
.env
(replace with actual values later):Environment variables:
PORT
: Express server portNODE_ENV
: Environment (affects logging behavior)INFOBIP_API_KEY
: API key from InfobipINFOBIP_BASE_URL
: Your unique base URL (e.g.,xxxxx.api.infobip.com
)INTERNAL_API_KEY
: Secret key to protect your API endpoint2. Building the Infobip SMS Service with Error Handling
Create a dedicated service to handle all Infobip API interactions. This promotes separation of concerns and improves testability.
Configure Logger (
src/config/logger.js
): Set up Winston for structured logging.Edit
src/services/infobipService.js
: This file will contain the logic for building the request and calling the Infobip ""Send SMS"" API endpoint (/sms/2/text/advanced
), now using the logger.console.*
withlogger.*
calls using the Winston logger. Added more contextual information to logs.sender
parameter in the JSDoc and implementation notes. It's now optional and only included if explicitly provided, encouraging reliance on Infobip's configured defaults if unsure.messageId
,status
,to
) instead of the full raw response on success.3. Creating the Express API Endpoint
Create the Express controller and route that will use the
infobipService
.Edit
src/controllers/campaignController.js
: This controller handles the incoming HTTP request, performs validation, calls the service, and sends back a curated response.to
field and a length check fortext
. Returns specific error messages using backticks for field names.messageId
,statusGroup
, andrecipient
from the service result. Error response is generic, advising to check logs, and explicitly does not include the rawerror.message
.Edit
src/routes/campaignRoutes.js
: Define the Express route and link it to the controller function.Edit
src/server.js
: Set up the main Express application, load environment variables, configure middleware (including logging), and mount the routes.dotenv.config()
: Still first.helmet
middleware.unhandledRejection
anduncaughtException
.Update
package.json
(Optional but Recommended): Add scripts to easily start the server.4. Infobip API Authentication and Configuration
This section details how to get your Infobip credentials and configure the application.
Obtain Infobip API Key and Base URL:
[your-unique-id].api.infobip.com
). Copy this value.nodejs-campaign-app
). Copy the generated key value immediately.Update
.env
File: Replace the placeholder values in your.env
file with the actual Base URL, API Key, and a secure internal API key.Environment Variable Purpose:
PORT
: Network port the Express server listens on.NODE_ENV
: Set toproduction
in deployed environments.INFOBIP_API_KEY
: Authenticates requests to the Infobip API (Authorization: App <key>
).INFOBIP_BASE_URL
: Correct domain for Infobip API endpoints (e.g.,yoursubdomain.api.infobip.com
). Does not includehttps://
.INTERNAL_API_KEY
: Used to secure your application's API endpoint (see Section 7 - Note: Section 7 is not present in the provided text).Campaign Registration (Crucial Reminder):
campaignId
in the API request body (src/services/infobipService.js
). Verify the requirements for your specific approved campaign. Failure to comply is a primary reason for message delivery issues.5. Production Error Handling with Winston Logging
Our implementation now includes structured logging with Winston and improved error handling. Let's discuss retries.
infobipService
). Detailed technical info is logged there using Winston. A curated error is thrown upwards. The controller catches this, logs the context, and sends a generic, safe error response to the client. Centralized handlers catch uncaught exceptions/rejections.src/config/logger.js
. It provides structured JSON logging, different levels based onNODE_ENV
, and timestamping.503 Service Unavailable
) might cause transient failures. Implementing retries can improve reliability for these cases.async-retry
oraxios-retry
.axios-retry
integrates directly with Axios, whileasync-retry
is a more general-purpose promise retry library.