Frequently Asked Questions
Use the Infobip API and Node.js SDK within an Express route to send SMS messages. Set up an endpoint to receive recipient numbers and message text, and handle sending via the Infobip client, along with error management and basic security.
It's the official Infobip Node.js SDK (`infobip-api-client-ts`), simplifying interactions with the Infobip API. It handles authentication, request construction, and response parsing, promoting cleaner and more reliable code compared to raw HTTP requests.
Storing API keys and configuration in `.env` files enhances security by keeping sensitive data out of your codebase. The `dotenv` package loads these variables into `process.env`, ensuring they are accessible but not directly embedded in the source code.
Implement `try...catch` blocks to handle errors from the Infobip SDK. Extract error details from the API response, and provide user-friendly error messages with appropriate HTTP status codes in your API response. Structured logging with context (timestamp, route, input) aids debugging. Consider PII implications before logging phone numbers.
For marketing SMS to US numbers, register your Brand and Campaigns with The Campaign Registry (TCR) via Infobip. This registration is required for Application-to-Person (A2P) 10-digit long code messaging and ensures deliverability while avoiding carrier filtering. Consult Infobip for 10DLC setup.
Use batch sending (`sms/2/text/advanced` endpoint) for sending the same message to multiple recipients or different messages to different recipients. This significantly reduces HTTP overhead compared to individual API calls per recipient, especially beneficial in marketing campaigns.
While a basic regex can perform initial checks, `google-libphonenumber` (and its Node.js port) is strongly recommended for production. It provides robust parsing, validation, and formatting according to international standards, crucial for E.164 compliance.
Legal regulations (TCPA, GDPR, CASL) mandate clear opt-out mechanisms. Include instructions in messages (e.g., "Reply STOP"), use webhooks to process opt-out keywords, and maintain a suppression list. Always check the subscribed status before sending marketing SMS.
Use `express-rate-limit` middleware in your Express app to prevent API abuse. Configure the time window and maximum requests per IP to control traffic and prevent brute-force attempts. Return informative error messages to clients exceeding the limit.
Platform as a Service (PaaS) options like Heroku, Render, or AWS Elastic Beanstalk simplify deployment and scaling. Containers (Docker, Kubernetes) offer environment consistency, while VPS (Linode, DigitalOcean) provides greater control but requires manual management.
Choose a database suitable for your needs and scale. Consider managed services like AWS RDS (for relational databases like PostgreSQL or MySQL) or MongoDB Atlas for document databases. Use an ORM like Prisma, Sequelize, or Mongoose to simplify interaction.
Yes, you can personalize SMS messages even when sending in bulk. The Infobip API allows sending different messages to different destinations in a batch. Construct personalized messages using data from your recipient database (name, preferences), but be mindful of PII policies.
Standard GSM-7 encoding allows 160 characters per segment. Unicode (UCS-2) allows 70. Infobip handles concatenation of longer messages automatically, but character count affects pricing and user experience. Be aware of segment limits.
Implement monitoring for API latency, throughput, error rates, and Infobip API performance. Use logging and tracing for debugging and performance analysis. Set up webhooks to receive DLRs from Infobip and track message delivery status in your database.
Build Production-Ready Node.js Marketing SMS Campaigns with Express and Infobip
This guide provides a comprehensive walkthrough for building a Node.js and Express application capable of sending marketing SMS messages using the Infobip API. We'll cover everything from initial project setup and core SMS sending functionality to essential production considerations like error handling, security, compliance (specifically mentioning 10DLC for US traffic), and deployment.
While this guide discusses many elements crucial for a production environment (security, compliance, monitoring), the provided code examples serve as a starting point. A truly production-ready system would require significant additions, particularly around database integration, robust endpoint security, comprehensive logging, and potentially advanced queueing mechanisms.
By the end of this tutorial, you will have a functional Express API endpoint that can receive requests to send SMS messages via Infobip, incorporating best practices for security, reliability, and compliance awareness.
Project Overview and Goals
What We'll Build:
We will create a Node.js application using the Express framework. This application will expose an API endpoint designed to:
Problem Solved:
This guide addresses the need for developers to integrate reliable SMS sending capabilities into their Node.js applications for marketing purposes, ensuring they are aware of compliance requirements and follow best practices for integration.
Technologies Used:
infobip-api-client-ts
) for a cleaner integration than raw HTTP calls.System Architecture:
Prerequisites:
curl
or Postman).Expected Outcome:
A running Node.js Express application with a functional
/send-sms
endpoint that uses the Infobip SDK to send messages. The guide will also detail the necessary steps and considerations discussed for making this production-ready, including compliance.1. Setting up the Project
Let's initialize our Node.js project and install the necessary dependencies.
Step 1: Create Project Directory
Open your terminal or command prompt and create a new directory for the project. Navigate into it.
Step 2: Initialize npm Project
Initialize a new Node.js project using npm. The
-y
flag accepts the default settings.This creates a
package.json
file.Step 3: Install Dependencies
We need Express for the server, the Infobip SDK for SMS sending,
dotenv
for environment variables, andexpress-rate-limit
for basic security.express
: Web framework.infobip-api-client-ts
: The official Infobip SDK for Node.js (works with JavaScript too). It simplifies API interactions compared to rawaxios
calls.dotenv
: Loads environment variables from a.env
file intoprocess.env
. Essential for keeping secrets out of code.express-rate-limit
: Basic middleware to limit repeated requests to public APIs.Step 4: Project Structure
Create a basic project structure.
server.js
: The main entry point for our Express application..env
: Stores sensitive information like API keys (will be created in the next step)..gitignore
: Specifies intentionally untracked files that Git should ignore (likenode_modules
and.env
).config/
: A directory for configuration files.config/infobipClient.js
: A module to initialize and configure the Infobip SDK client.Step 5: Configure
.gitignore
Add the following lines to your
.gitignore
file to prevent committing sensitive data and unnecessary files:Step 6: Set Up Environment Variables (
.env
)Create a file named
.env
in the project root. You'll need your Infobip API Key and Base URL.xxxxxx.api.infobip.com
.Add the following lines to your
.env
file, replacing the placeholders with your actual credentials:INFOBIP_API_KEY
: Your secret API key for authentication.INFOBIP_BASE_URL
: The custom domain provided by Infobip for API requests.PORT
: The port number your Express server will run on.Why
.env
? Storing configuration, especially secrets like API keys, in environment variables is crucial for security. It prevents hardcoding sensitive data directly into your source code, making it easier to manage different environments (development, staging, production) and reducing the risk of accidental exposure.2. Implementing Core Functionality (Sending SMS)
Now, let's configure the Infobip SDK client and write the logic to send an SMS.
Step 1: Configure the Infobip Client
Open
config/infobipClient.js
and add the following code to initialize the SDK:dotenv
..env
file is missing or misconfigured.Infobip
client, passing ourbaseUrl
,apiKey
, and specifyingAuthType.ApiKey
.Step 2: Create the Express Server and SMS Sending Route
Open
server.js
and set up the Express application and the route for sending SMS.express
and our configuredinfobipClient
.express.json()
middleware to parse incoming JSON request bodies.POST /send-sms
route handles the logic:to
(recipient phone number) andtext
(message content) from the request body.google-libphonenumber
) is essential for production.infobipClient.channels.sms.send()
with the message details.PENDING
orDELIVERED
status groups. Includes a warning that other states might exist and recommends checking Infobip docs.try...catch
block handles errors, logs them, and sends an appropriate error response, extracting details from the Infobip response if possible./health
endpoint is included.app
for testing purposes.Why the SDK? Using the official Infobip SDK (
infobip-api-client-ts
) abstracts away the complexities of making raw HTTP requests (constructing URLs, setting headers, handling authentication tokens, parsing responses). It provides typed methods and often includes built-in retry logic or better error handling structures, leading to cleaner, more maintainable, and less error-prone code.3. Building a Complete API Layer
Our core functionality relies on the
POST /send-sms
endpoint. Let's detail its usage and provide testing examples.API Endpoint Documentation:
Endpoint:
POST /send-sms
Description: Sends a single SMS message to a specified recipient via Infobip.
Authentication: None implemented directly on our API layer in this basic example (though the server authenticates with Infobip using the API Key). In production, you would secure this endpoint (e.g., with API keys, JWT, OAuth).
Request Body: JSON
to
(string, required): The recipient's phone number in E.164 format (e.g.,+14155552671
).text
(string, required): The content of the SMS message.Success Response (200 OK): JSON
Error Responses:
400 Bad Request
: Missing fields or invalid phone number format.401 Unauthorized
(if Infobip rejects the API Key):500 Internal Server Error
(or other status codes from Infobip): General failure during processing or sending.Testing with
curl
:Start your server:
Send a request: Open another terminal window and run the following
curl
command. Replace<your_phone_number_e164>
with your actual phone number in E.164 format (the one registered with your Infobip free trial account if applicable).You should receive a
200 OK
response in the terminal and an SMS message on your phone shortly after.Testing with Postman:
POST
.http://localhost:3000/send-sms
.4. Integrating with Necessary Third-Party Services (Infobip)
We've already integrated Infobip using the SDK. This section reiterates the configuration details.
Configuration Steps:
.env
file in your project root. Never commit.env
files to version control.dotenv
package early in your application (require('dotenv').config();
) to load these variables intoprocess.env
.config/infobipClient.js
.Environment Variable Details:
INFOBIP_API_KEY
:INFOBIP_BASE_URL
:xxxxxx.api.infobip.com
.PORT
:3000
is a common default for development.Fallback Mechanisms:
For critical SMS notifications, consider:
async-retry
can help.5. Implementing Proper Error Handling, Logging, and Retry Mechanisms
We've implemented basic error handling, but let's refine logging.
Error Handling Strategy:
try...catch
).catch
block (error.response.data
).{ ""error"": ""message"", ""details"": { ... } }
).Logging:
Our current
console.log
andconsole.error
are basic. For production, use a dedicated logging library likewinston
orpino
for structured logging, different log levels, and configurable outputs (file, console, external services).Example with Basic Logging Refinement:
Modify the
catch
block inserver.js
:to
) and suggests considering masking or omission in production environments due to potential PII (Personally Identifiable Information) concerns.Retry Mechanisms:
While the Infobip SDK might handle some retries, explicitly adding them for specific error types (like network timeouts or 5xx errors) can improve resilience.
async-retry
simplify this. You'd wrap theinfobipClient.channels.sms.send(...)
call within the retry logic. This is generally more applicable to backend processes than direct API responses where timeouts might be shorter.6. Creating a Database Schema and Data Layer (Conceptual)
For a real marketing campaign system, you need to store recipient information, opt-in status, and potentially campaign details.
Conceptual Schema (using pseudocode/simplified Prisma example):
Data Layer Implementation:
recipientRepository.js
) to keep route handlers clean.prisma migrate dev
,sequelize db:migrate
) to manage schema changes systematically.Integration:
Instead of sending to a single number from the request body, your API endpoint might:
campaignId
orlistId
.Note: Implementing a full database layer is beyond the scope of this initial guide but is a critical next step for managing marketing lists and campaigns effectively.
7. Adding Security Features
Protecting your API and user data is paramount.
Input Validation and Sanitization:
to
andtext
. Use libraries likejoi
orexpress-validator
for more complex validation rules (length, format, allowed characters). For phone numbers,google-libphonenumber
is highly recommended for robust parsing and validation.Rate Limiting:
Prevent abuse and brute-force attacks by limiting the number of requests a client can make.
Implementation with
express-rate-limit
:Add this middleware near the top of
server.js
, afterexpress.json()
:windowMs
andmax
based on your expected traffic and security requirements.API Key Security:
.env
files and environment variables in deployment.Securing Your Endpoint:
The
/send-sms
endpoint itself is currently open. In production, you would need to secure it:8. Handling Special Cases Relevant to the Domain
Phone Number Formatting (E.164):
+14155552671
,+442071838750
). This includes the+
sign and the country code.google-libphonenumber
(via its Node.js port) are the standard for parsing, validating, and formatting phone numbers globally and are strongly recommended over basic regex for production use.SMS Character Limits and Encoding:
Opt-Out Handling (Compliance Requirement):
STOP
,UNSUBSCRIBE
, etc., keywords to update the recipient'ssubscribed
status in your database immediately.subscribed
status before sending any marketing message.Sender ID:
InfoSMS
in the code comment).9. Implementing Performance Optimizations
Batch Sending:
Capability: The Infobip
sms/2/text/advanced
endpoint (which the SDK uses) supports sending the same message text to multiple destinations in a single API call, or different messages to different destinations.Benefit: Reduces HTTP overhead compared to making one API call per recipient.
Implementation: Modify the
messages
array structure passed to the SDK:Check the specific SDK documentation for the most efficient way to structure batch requests.
Asynchronous Processing:
202 Accepted
) indicating the job is queued.Database Query Optimization:
phoneNumber
andsubscribed
status).phoneNumber
).10. Adding Monitoring, Observability, and Analytics
Health Checks:
/health
endpoint. Expand this to check database connectivity or other critical dependencies if applicable. Monitoring services frequently poll this endpoint.Performance Metrics:
/send-sms
endpoint.infobipClient.channels.sms.send()
call.Logging and Tracing:
Delivery Reports (DLRs):
Analytics:
11. Writing Unit and Integration Tests
Testing ensures your application works correctly and prevents regressions.
Unit Tests:
jest
ormocha
with assertion libraries likechai
. Use spies/stubs/mocks (e.g.,sinon
orjest.fn()
) to isolate dependencies like the Infobip SDK or database calls.Integration Tests:
Focus: Test the interaction between different parts of your application, including the API endpoint and potentially mocked external services.
Tools: Use
supertest
along withjest
ormocha
to make HTTP requests to your running (or in-memory) Express app. Mock the Infobip SDK to avoid sending real SMS during tests.Example (
supertest
withjest
):jest.mock
to replace the actualinfobipClient
with a mock, allowing you to control its behavior (mockResolvedValue
,mockRejectedValue
) and assert that it was called correctly (toHaveBeenCalledWith
).supertest
to send requests to/send-sms
and/health
and checks status codes and response bodies.12. Addressing Compliance and Regulatory Requirements
Sending marketing SMS, especially in bulk, is subject to strict regulations. Failure to comply can result in significant fines and carrier blocking.
Key Compliance Areas:
Disclaimer: This is not legal advice. Consult with legal counsel familiar with telecommunications law in your target regions to ensure full compliance.
Integration:
subscribed
field and potentially a timestamp for opt-in/opt-out.subscribed
status before sending.STOP
replies automatically.13. Deployment Considerations
Moving from development to production requires careful planning.
Environment Configuration:
.env
locally, system environment variables or secrets management in production) for all configuration, especially secrets (API keys, database URLs). Do not hardcode secrets.Hosting Options:
Process Management:
pm2
ornodemon
(for development) to keep your Node.js application running, handle crashes, and manage logs.Database:
Load Balancing:
CI/CD Pipeline:
Security Hardening:
npm audit
).Monitoring and Alerting (Production Grade):
Conclusion
This guide walked through building a foundational Node.js and Express application for sending marketing SMS messages using the Infobip API and SDK. We covered project setup, core sending logic, API design, essential integrations, error handling, security basics, compliance awareness (including 10DLC), performance considerations, testing strategies, and deployment factors.
Remember, the provided code is a starting point. Building a truly robust, scalable, and compliant production system requires further development, particularly in database integration, advanced error handling, comprehensive logging/monitoring, queueing for large volumes, rigorous testing, and strict adherence to legal requirements.
By following these steps and considerations, you are well-equipped to integrate reliable and compliant SMS marketing capabilities into your Node.js applications. Always prioritize security, compliance, and user experience when working with communication APIs.