Developer Quick-Start: Build a robust Node.js application using Express to send SMS messages via the Infobip API. This step-by-step tutorial covers API authentication, 10DLC compliance, error handling, and production-ready logging with Winston. 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.
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:
- Express API endpoint to trigger SMS sends
- Secure Infobip API integration using API keys
- Input validation and error handling
- Structured application architecture
- Production logging and API security
Technology Stack:
- Node.js: JavaScript runtime environment
- Express: Minimal Node.js web framework
- Axios: Promise-based HTTP client for Infobip API requests
- dotenv: Environment variable management for secure configuration
- Winston: Structured logging library
- Infobip API: SMS messaging service
System Architecture:
graph LR
A[Client/Trigger<br>(e.g., Frontend,<br>Scheduler, etc.)] --> B{Node.js/Express App<br>(API Endpoint)};
B --> C[Infobip API<br>(SMS Sending)];
subgraph B [Node.js/Express App]
direction TB
B1[Validate Request] --> B2[Build Infobip Payload];
B2 --> B3[Call Infobip API];
B3 --> B4[Handle Response/Error];
end
Prerequisites:
- Node.js and npm: Installed on your development machine (Download Node.js)
- Infobip Account: Register at infobip.com/signup
- Infobip API Key and Base URL: Obtain from your Infobip account dashboard
- Verified Phone Number (Free Trial): Free trial accounts can only send SMS to verified numbers
- β οΈ Critical: 10DLC Campaign Registration (US Traffic): For US Application-to-Person (A2P) SMS using 10-digit long codes, you must register a Brand and Campaign through Infobip. This is mandatory and enforced by US carriers. Sending without proper registration will cause message failures. See Infobip 10DLC Documentation for the registration process. This guide assumes you have an approved campaign.
Final Outcome:
You'll have a functional Express application with a secured API endpoint
(/api/campaign/send-sms) that:
- Accepts destination phone number and message text
- Validates input
- Sends SMS via Infobip
- Logs actions and errors
- Returns structured results
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:
mkdir infobip-sms-campaign-app
cd infobip-sms-campaign-app
- Initialize npm: Initialize the project (accept defaults or customize):
npm init -y
- Install Dependencies: Install Express, Axios, dotenv, and Winston:
npm install express axios dotenv winston
- Create Project Structure: Set up the directory structure:
mkdir src
mkdir src/routes
mkdir src/services
mkdir src/controllers
mkdir src/config
mkdir src/middleware
touch src/server.js
touch src/routes/campaignRoutes.js
touch src/services/infobipService.js
touch src/controllers/campaignController.js
touch src/config/logger.js
touch src/middleware/auth.js
touch .env
touch .gitignore
Directory structure:
- src/: All source code
- src/routes/: Express route definitions
- src/services/: External service interaction logic (Infobip)
- src/controllers/: Request handlers
- src/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 ignore
- Configure
.gitignore: Add these entries to prevent committing sensitive files:
# .gitignore
node_modules
.env
npm-debug.log
*.log
- Set up Environment Variables: Add placeholders to
.env(replace with actual values later):
.env
# .env
# Server Configuration
PORT=3000
NODE_ENV=development
# Infobip API Credentials
INFOBIP_API_KEY=YOUR_INFOBIP_API_KEY
INFOBIP_BASE_URL=YOUR_INFOBIP_BASE_URL
# Internal API Security
# Generate a strong random key for production
INTERNAL_API_KEY=YOUR_SECRET_API_KEY_FOR_INTERNAL_ACCESS
Environment variables:
- PORT: Express server port
- NODE\_ENV: Environment (affects logging behavior)
- INFOBIP\_API\_KEY: API key from Infobip
- INFOBIP\_BASE\_URL: Your unique base URL (e.g., xxxxx.api.infobip.com)
- INTERNAL\_API\_KEY: Secret key to protect your API endpoint
2. 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.
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
format: winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.errors({ stack: true }),
winston.format.splat(),
winston.format.json()
),
defaultMeta: { service: 'infobip-sms-service' },
transports: [
],
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
),
}));
}
module.exports = 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.
const axios = require('axios');
const logger = require('../config/logger');
const INFOBIP_API_KEY = process.env.INFOBIP_API_KEY;
const INFOBIP_BASE_URL = process.env.INFOBIP_BASE_URL;
const buildUrl = () => {
if (!INFOBIP_BASE_URL) {
logger.error('INFOBIP_BASE_URL environment variable is not set.');
throw new Error('Infobip configuration error: Base URL is missing.');
}
return `https://${INFOBIP_BASE_URL}/sms/2/text/advanced`;
};
const buildHeaders = () => {
if (!INFOBIP_API_KEY) {
logger.error('INFOBIP_API_KEY environment variable is not set.');
throw new Error('Infobip configuration error: API Key is missing.');
}
return {
'Authorization': `App ${INFOBIP_API_KEY}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
};
};
const buildRequestBody = (destinationNumber, messageText, sender) => {
if (!destinationNumber || !messageText) {
logger.warn('Attempted to build request body with missing destination or text.', { destinationNumber, messageText });
throw new Error('Destination number and message text are required.');
}
const payload = {
messages: [
{
destinations: [{ to: destinationNumber }],
text: messageText,
...(sender && { from: sender }),
},
],
};
logger.debug('Built Infobip request payload.', { payload });
return payload;
};
const sendSms = async (destinationNumber, messageText, sender) => {
let url, headers, requestBody;
try {
url = buildUrl();
headers = buildHeaders();
requestBody = buildRequestBody(destinationNumber, messageText, sender);
logger.info(`Attempting to send SMS to ${destinationNumber} via Infobip...`);
const response = await axios.post(url, requestBody, { headers: headers });
logger.info('Infobip API Response Status:', { status: response.status });
logger.debug('Infobip API Response Body:', { data: response.data });
const messageInfo = response.data?.messages?.[0];
if (messageInfo) {
const status = messageInfo.status;
if (status?.groupName === 'PENDING' || status?.groupName === 'DELIVERED') {
logger.info(`SMS submitted successfully for ${destinationNumber}. Status: ${status.name}, Message ID: ${messageInfo.messageId}`);
} else {
logger.warn(`SMS submission for ${destinationNumber} resulted in status: ${status?.name || 'Unknown'} (${status?.description || 'N/A'}), Group: ${status?.groupName || 'Unknown'}`, { messageId: messageInfo.messageId });
}
return {
messageId: messageInfo.messageId,
status: status,
to: messageInfo.to
};
} else {
logger.warn(`Unexpected response structure received from Infobip for ${destinationNumber}.`, { responseData: response.data });
return { rawResponse: response.data, warning: ""Unexpected response structure"" };
}
} catch (error) {
logger.error('Error sending SMS via Infobip.', {
message: error.message,
url: url,
destination: destinationNumber,
stack: error.stack,
});
let errorMessage = 'Failed to send SMS due to an internal error.';
if (error.response) {
logger.error('Infobip API Error Response:', {
status: error.response.status,
headers: error.response.headers,
data: error.response.data,
});
const serviceException = error.response.data?.requestError?.serviceException;
if (serviceException) {
errorMessage = `Infobip API Error: ${serviceException.text || 'Unknown error'} (ID: ${serviceException.messageId || 'N/A'})`;
} else {
errorMessage = `Infobip API request failed with status ${error.response.status}.`;
}
throw new Error(errorMessage);
} else if (error.request) {
logger.error('Infobip Error: No response received.', { request: error.request });
errorMessage = 'No response received from Infobip API. Check network connectivity and Base URL.';
throw new Error(errorMessage);
} else {
errorMessage = `Error setting up Infobip request: ${error.message}`;
throw new Error(errorMessage);
}
}
};
module.exports = {
sendSms,
_buildUrl: buildUrl,
_buildHeaders: buildHeaders,
_buildRequestBody: buildRequestBody
};
- Logging: Replaced console.\* with logger.\* calls using the Winston logger. Added more contextual information to logs.
- Error Handling: Logs detailed technical errors server-side and throws a more user-friendly (but still informative) error message for the controller layer.
- Sender ID: Added stronger warnings about the 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.
- Response Handling: Returns a curated object with key information (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.
const infobipService = require('../services/infobipService');
const logger = require('../config/logger');
const E164_REGEX = /^\+[1-9]\d{1,14}$/;
const sendCampaignSms = async (req, res) => {
const { to, text, sender } = req.body;
const errors = [];
if (!to) {
errors.push('Missing required field: `to` (phone number)');
} else if (!E164_REGEX.test(to)) {
errors.push('Invalid phone number format for `to`. Use E.164 format (e.g., +14155552671).');
}
if (!text) {
errors.push('Missing required field: `text` (message content)');
} else if (text.length > 1600) {
errors.push('Message text exceeds maximum allowed length (1600 characters).');
}
if (errors.length > 0) {
logger.warn('Invalid request to send SMS.', { errors, requestBody: req.body });
return res.status(400).json({
success: false,
message: 'Invalid request payload.',
errors: errors,
});
}
try {
const result = await infobipService.sendSms(to, text, sender);
res.status(200).json({
success: true,
message: 'SMS submitted successfully to Infobip.',
details: {
messageId: result?.messageId,
statusGroup: result?.status?.groupName,
recipient: result?.to,
}
});
} catch (error) {
logger.error('Error processing send SMS request in controller.', {
errorMessage: error.message,
recipient: to,
stack: error.stack
});
res.status(500).json({
success: false,
message: 'Failed to send SMS due to a server error. Please check server logs for details or contact support.',
});
}
};
module.exports = {
sendCampaignSms,
};
- Validation: Added basic E.164 regex validation for the to field and a length check for text. Returns specific error messages using backticks for field names.
- Curated Responses: Success response now includes only messageId, statusGroup, and recipient from the service result. Error response is generic, advising to check logs, and explicitly does not include the raw error.message.
- Logging: Logs validation failures and errors occurring within the controller itself.
- Edit
src/routes/campaignRoutes.js: Define the Express route and link it to the controller function.
const express = require('express');
const campaignController = require('../controllers/campaignController');
const router = express.Router();
router.post('/send-sms', campaignController.sendCampaignSms);
module.exports = router;
- Edit
src/server.js: Set up the main Express application, load environment variables, configure middleware (including logging), and mount the routes.
require('dotenv').config();
const express = require('express');
const helmet = require('helmet');
const campaignRoutes = require('./routes/campaignRoutes');
const logger = require('./config/logger');
const app = express();
app.use(helmet());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
logger.info(`Incoming Request: ${req.method} ${req.path}`, {
ip: req.ip,
userAgent: req.get('User-Agent'),
body: req.body
});
res.on('finish', () => {
logger.info(`Request Finished: ${req.method} ${req.path} - Status: ${res.statusCode}`, {
duration: `${Date.now() - res.locals.startTime}ms`
});
});
res.locals.startTime = Date.now();
next();
});
app.use('/api/campaign', campaignRoutes);
app.get('/health', (req, res) => {
res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() });
});
app.use((req, res, next) => {
res.status(404).json({ message: 'Resource not found at ' + req.originalUrl });
});
app.use((err, req, res, next) => {
logger.error('Unhandled error caught by central handler:', {
message: err.message,
stack: err.stack,
url: req.originalUrl,
method: req.method,
ip: req.ip,
});
const statusCode = err.status || 500;
const responseMessage = process.env.NODE_ENV === 'production'
? 'Internal Server Error'
: err.message;
res.status(statusCode).json({
message: 'An unexpected error occurred.',
error: responseMessage
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
logger.info(`Server listening on port ${PORT}`);
logger.info(`Current environment: ${process.env.NODE_ENV || 'development'}`);
if (!process.env.INFOBIP_API_KEY || !process.env.INFOBIP_BASE_URL) {
logger.warn('Infobip API Key or Base URL not found in environment variables. API calls will fail.');
}
if (!process.env.INTERNAL_API_KEY && process.env.NODE_ENV === 'production') {
logger.warn('INTERNAL_API_KEY is not set. The API endpoint security is compromised in production!');
}
});
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection at:', { promise, reason: reason.stack || reason });
});
process.on('uncaughtException', (error) => {
logger.error('Uncaught Exception:', { message: error.message, stack: error.stack });
process.exit(1);
});
- dotenv.config(): Still first.
- Logging: Integrated Winston for request logging and centralized error handling.
- Security: Added helmet middleware.
- Error Handling: Enhanced the final error handler to use Winston and provide less detail in production. Added global handlers for unhandledRejection and uncaughtException.
- Startup Checks: Added warnings if essential keys (Infobip or internal API key) are missing.
- Update
package.json(Optional but Recommended): Add scripts to easily start the server.
"scripts": {
"start": "node src/server.js",
"dev": "nodemon src/server.js",
"lint": "eslint .",
"test": "echo \"Error: no test specified\" && exit 1"
},
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:
- Log in to your Infobip account portal.
- Navigate to the Developers section or API Keys management area.
- Base URL: Find your unique API Base URL (e.g., [your-unique-id].api.infobip.com). Copy this value.
- API Key: Generate a new API key. Give it a descriptive name (e.g., nodejs-campaign-app). Copy the generated key value immediately.
- Security Note: Treat your API key like a password. Use environment variables; do not commit it to version control.
- Update
.envFile: Replace the placeholder values in your.envfile with the actual Base URL, API Key, and a secure internal API key.
.env
# .env (Example values - Replace with your actual credentials!)
PORT=3000
NODE_ENV=development
# Infobip API Credentials
INFOBIP_API_KEY=abcdef1234567890abcdef1234567890-abcdef12-abcd-1234-abcd-abcdef123456
INFOBIP_BASE_URL=z9x8y7.api.infobip.com
# Internal API Security (Generate a strong random string for this)
INTERNAL_API_KEY=Str0ngS3cr3tK3yF0rYourAPI!
- Environment Variable Purpose:
- PORT: Network port the Express server listens on.
- NODE\_ENV: Set to production 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 include https://.
- 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):
- As highlighted in the prerequisites, simply having an API key is often insufficient, especially for A2P 10DLC in the US. You must have a registered and approved campaign linked to your sender number(s).
- Use the Infobip portal or the Number Registration API to register your Brand and Campaign. This involves detailing your use case, providing message samples, and explaining opt-in procedures.
- Allow time for Infobip Compliance review and approval.
- Only after approval can you reliably send messages using the associated sender ID/number. You might need to include a 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.
- Consistent Error Strategy: Errors are caught at the lowest level possible (e.g., 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.
- Logging:
- We now use Winston configured in src/config/logger.js. It provides structured JSON logging, different levels based on NODE\_ENV, and timestamping.
- Logs include context like service name, request details, and error stacks.
- In production, configure transports to write logs to files or stream them to external aggregation services (ELK, Datadog, Splunk).
- Retry Mechanisms:
- Network glitches or temporary Infobip issues (like 503 Service Unavailable) might cause transient failures. Implementing retries can improve reliability for these cases.
- Use libraries like
async-retryoraxios-retry. axios-retry integrates directly with Axios, while async-retry is a more general-purpose promise retry library. - Caution: Only retry on specific, recoverable error types (network errors, 5xx server errors). Do not retry on client errors (4xx) or non-recoverable errors.
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 β