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.
This guide provides a step-by-step walkthrough for building a robust Node.js application using the Express framework to send SMS messages via the Infobip API, specifically tailored for marketing campaign scenarios.
We will build a backend service capable of accepting requests to send targeted SMS messages, integrating securely with Infobip, handling errors gracefully, and incorporating best practices for production readiness. This service acts as a foundational component for executing SMS marketing campaigns triggered by user actions, schedules, or other business logic.
Project Goals:
Technology Stack:
.env
file for secure configuration.System Architecture:
Prerequisites:
Final Outcome:
By the end of this guide, you will have a functional Express application with a secured API endpoint (
/api/campaign/send-sms
) that accepts a destination phone number and message text, validates the input, sends the SMS via Infobip using a dedicated service, logs actions and errors, and returns a curated result. The application will be configured securely using environment variables.1. Setting up the project
Let's initialize the Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal or command prompt and create a new directory for your project. Navigate into it.
Initialize npm: Initialize the project using npm. You can accept the defaults or customize them.
This creates a
package.json
file.Install Dependencies: Install Express for the web server, Axios for HTTP requests, dotenv for environment variables, and Winston for logging.
Create Project Structure: Set up a basic directory structure for better organization.
src/
: Contains all the source code.src/routes/
: Holds Express route definitions.src/services/
: Contains logic for interacting with external services (like Infobip).src/controllers/
: Handles incoming requests and utilizes services.src/config/
: Holds configuration files, like the logger setup.src/middleware/
: Contains custom middleware functions (e.g., authentication).src/server.js
: The main entry point for the application..env
: Stores environment variables (API keys, etc.). Never commit this file to Git..gitignore
: Specifies files and directories that Git should ignore.Configure
.gitignore
: Addnode_modules
and.env
to your.gitignore
file to prevent committing them.Set up Environment Variables: Open the
.env
file and add placeholders for your Infobip credentials, server port, and a potential internal API key for securing your own endpoint. You will replace the placeholder values later.PORT
: The port your Express server will listen on.NODE_ENV
: Helps configure behavior (e.g., logging levels) based on the environment.INFOBIP_API_KEY
: Your API key obtained from Infobip.INFOBIP_BASE_URL
: Your unique base URL provided by Infobip (e.g.,xxxxx.api.infobip.com
).INTERNAL_API_KEY
: A secret key you define to protect your own API endpoint.2. Implementing core functionality - The Infobip Service
We'll create a dedicated service to handle all interactions with the Infobip API. This promotes separation of concerns and makes the code easier to test and maintain.
Configure Logger (
src/config/logger.js
): Set up a reusable Winston logger.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. Building the API layer
Now, let's 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. Integrating with Infobip (Configuration Details)
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. Implementing error handling, logging, and retry mechanisms
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.