Frequently Asked Questions
Use the Infobip Node.js SDK and Express to build a service that interacts with the Infobip API. This allows you to send SMS messages programmatically by making API calls to your Infobip account, simplifying the integration process.
The Infobip Node.js SDK (@infobip-api/sdk) is a pre-built library that simplifies interaction with the Infobip API. It handles authentication and provides convenient methods for sending SMS messages and other communication tasks, reducing boilerplate code.
Node.js and Express provide a popular, efficient, and well-supported foundation for building APIs and microservices. Their scalability makes them suitable for handling potentially high volumes of SMS requests.
A dedicated microservice is beneficial when you need to centralize SMS sending logic, securely manage API credentials, provide a consistent interface, and simplify integration for multiple applications that require SMS capabilities.
Yes, you can use a custom alphanumeric sender ID (e.g., your brand name) to improve message recognition, subject to Infobip's guidelines and local regulations, which may require registration.
Store your Infobip Base URL and API Key as environment variables (INFOBIP_BASE_URL and INFOBIP_API_KEY) in a .env file for development. Never hardcode these credentials directly in your code, and in production, use proper environment variable management within your deployment platform.
Dotenv is a package that loads environment variables from a .env file into process.env, making it easy to manage configuration values, especially API keys and other sensitive data that shouldn't be committed to version control.
Implement try...catch blocks to handle errors from the Infobip SDK and service layer. Provide informative error messages and log details like the error response from Infobip for debugging. Consider using a dedicated error tracking service in production.
You should consider storing contact details (phone numbers, opt-in status), campaign information (messages, schedules), message logs (status, recipient, costs), and opt-out records for analytics, reporting, and compliance.
Use the isMobilePhone validator from express-validator or regular expressions to ensure phone numbers are in a valid international format and sanitize input to prevent vulnerabilities. Dedicated libraries like libphonenumber-js can help improve validation accuracy.
Secure your API keys, implement robust input validation using libraries like express-validator, use rate limiting (express-rate-limit) to prevent abuse, enforce HTTPS, and add authentication/authorization if your service is exposed externally.
Express-rate-limit is middleware that helps protect your API from abuse by limiting the number of requests from a given IP address within a specified time window. This can prevent overload and denial-of-service attacks.
Organize your project with separate directories for routes, controllers, and services. Routes define API endpoints, controllers handle requests and interact with services, and services encapsulate the logic for sending SMS using the Infobip SDK.
Logging provides crucial information for debugging, monitoring, and troubleshooting. Use a structured logging library to record timestamps, log levels, request IDs, and error details, and configure appropriate log destinations for analysis.
The /health endpoint is a simple way to check the status and availability of your service. It typically returns a 200 OK response with a timestamp or other relevant information, allowing monitoring systems to verify that the service is running.
Build a Node.js Express SMS Service with Infobip API Integration
Build a production-ready Node.js and Express application to send SMS messages using the Infobip API. This comprehensive guide covers creating a scalable SMS microservice for marketing campaigns, transactional notifications, and automated messaging with secure API integration, error handling, and validation.
You'll implement the official Infobip Node.js SDK for simplified API integration, configure secure environment variables for API authentication, build RESTful endpoints with Express, and implement production-grade error handling. By the end, you'll have a fully functional SMS service with security features and rate limiting.
Overview: Building an SMS microservice with Node.js and Infobip
Goal: Create a dedicated Node.js Express microservice to send SMS messages via the Infobip platform. This service exposes a simple API endpoint that other applications within your infrastructure can call to trigger SMS sends.
Problem solved: Centralizes SMS sending logic, securely manages Infobip credentials, provides a consistent interface for sending messages, and simplifies integration for other services needing SMS capabilities.
Technologies:
@infobip-api/sdk
): Simplifies interaction with the Infobip API by providing pre-built methods and handling authentication..env
file intoprocess.env
.Why these choices?
dotenv
is standard practice for managing environment-specific configurations and secrets securely in development.System architecture:
Prerequisites:
Final outcome: A running Express application with a
/api/sms/send
endpoint that accepts a phone number and message text, sends the SMS via Infobip, and returns a success or error response.Set up your Node.js SMS project
Initialize your Node.js project and install the necessary dependencies.
Create project directory: Open your terminal and create a new directory for the project.
Initialize Node.js project: Create a
package.json
file to manage project details and dependencies.(Alternatively, use
yarn init -y
if you prefer Yarn)Install dependencies: Install Express for the web server, the Infobip SDK for SMS sending, and
dotenv
for managing environment variables.(Or
yarn add express @infobip-api/sdk dotenv
)Create project structure: Set up a basic structure for organization.
src/
: Contains your main application code.src/routes/
: Defines API routes.src/controllers/
: Handles incoming requests and interacts with services.src/services/
: Contains business logic, like interacting with the Infobip SDK.src/server.js
: The main entry point for your Express 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.Create basic Express server (
src/server.js
): Create a minimal Express server to verify your setup works.require('dotenv').config()
: Loads variables from the.env
file.express.json()
: Middleware to parse incoming JSON request bodies./health
check endpoint./api/sms
.Update
package.json
scripts: Add a convenientstart
script to run the server.Note: The dependency versions listed (
^2.0.0
,^16.0.0
,^4.17.0
) are examples. Install compatible versions or update them based on the latest stable releases.You now have a basic Node.js Express project structure ready for implementing the SMS functionality.
Implement the Infobip SMS service layer
Encapsulate the Infobip SDK interaction within a dedicated service file.
Configure environment variables (
.env
): Open the.env
file and add placeholders for your Infobip Base URL and API Key. Obtain these from your Infobip account dashboard in the next step.Create Infobip service (
src/services/infobipService.js
): This service initializes the Infobip client and provides a function to send SMS.Infobip
client andAuthType
enum from the SDK.infobipClient
using the Base URL and API Key from.env
.sendSms
function takes the recipient, message, and optional sender ID.libphonenumber-js
, message length) for production use./sms/2/text/advanced
endpoint, which the SDK uses).infobipClient.channels.sms.send()
within atry...catch
block.Build the Express API for SMS sending
Create the Express route and controller to handle incoming requests to send SMS.
Create SMS controller (
src/controllers/smsController.js
): This controller handles the logic for the/send
route. You'll add more robust validation in section 7.infobipService
.recipientNumber
andmessageText
fromreq.body
.infobipService.sendSms
within atry...catch
block.200 OK
response with the Infobip result on success.400 Bad Request
for validation errors or500 Internal Server Error
for service errors.Define SMS routes (
src/routes/smsRoutes.js
): This file defines the specific endpoints under the/api/sms
prefix.smsController
.POST
route at/send
that maps to thesendSingleSms
controller function.Your API layer is now set up. The
server.js
file already mounts these routes under/api/sms
.Configure Infobip API credentials
Connect your application to your Infobip account.
Log in to Infobip: Go to the Infobip Portal and log in. The exact navigation within the Infobip portal may change over time.
Find your API Key:
Find your Base URL:
xxxxx.api.infobip.com
.Update
.env
file: Paste the copied values into your.env
file:Sender ID (optional but recommended):
.env
or pass it in the API request body (senderId
field).Security: Your Infobip API key grants access to your account and potentially incurs costs. Never commit your
.env
file or expose your API key in client-side code or public repositories. Use environment variables in your deployment environment.Implement production-grade error handling
Robust error handling and logging are vital for production systems.
infobipService.js
):try...catch
block already catches errors from the SDK call.error.response.data
) when available, which is crucial for debugging API issues (e.g., invalid number format, insufficient funds, permission errors).smsController.js
):try...catch
block catches errors thrown by the service layer.400 Bad Request
/422 Unprocessable Entity
for client-side errors (missing parameters, invalid format – see validation section).500 Internal Server Error
for server-side or downstream errors (Infobip API unavailable, unexpected exceptions).success: false
flag and anerror
message.server.js
):winston
,pino
) and potentially error tracking services (e.g., Sentry).console.log
andconsole.error
. For production:async-retry
can simplify this. Wrap theinfobipClient.channels.sms.send
call within the retry logic ininfobipService.js
.Design your SMS database schema (optional)
While this guide focuses purely on the sending mechanism_ a real-world marketing campaign system requires data persistence. This service could be extended or interact with other services managing:
Contacts (contact_id PK_ phone_number UNIQUE_ first_name_ last_name_ opt_in_status_ created_at_ updated_at)
Campaigns (campaign_id PK_ name_ message_template_ target_segment_ schedule_time_ status_ created_at)
MessageLogs (log_id PK_ infobip_message_id UNIQUE_ contact_id FK_ campaign_id FK_ status_ status_group_ error_code_ sent_at_ delivered_at_ cost)
OptOuts (phone_number PK_ opted_out_at)
Implementation:
Scope: Implementing the full database layer is beyond the scope of this specific Infobip integration guide.
Secure your SMS API with validation and rate limiting
Security is paramount_ especially when handling user data and external APIs.
Secure API key management: Already covered by using
.env
and environment variables in production. Never hardcode keys.Input validation:
The initial controller (
smsController.js
) has minimal validation. Replace it usingexpress-validator
for robust_ declarative validation.Install the library:
Update controller (
src/controllers/smsController.js
): Define validation rules and a middleware function to handle errors. Export these along with the main controller function.Update routes (
src/routes/smsRoutes.js
): Apply the validation rules and middleware to the route definition before the controller function.Rate limiting: Protect your API from abuse and accidental loops. Use middleware like
express-rate-limit
.HTTPS: Always use HTTPS in production to encrypt data in transit. This is typically handled at the load balancer or reverse proxy level (e.g., Nginx, Caddy, Cloudflare, AWS ELB), not directly in the Node.js application code.
Authentication/authorization: If this service is exposed externally or consumed by multiple internal clients, implement proper authentication (e.g., API keys required in headers, JWT validation) to ensure only authorized systems can trigger SMS sends. This is beyond the scope of this basic setup but crucial for real-world deployments.
Testing your Infobip SMS integration
Before deploying to production, test your SMS service thoroughly:
Test with curl or Postman:
Verify response structure:
200 OK
withsuccess: true
and Infobip response data422 Unprocessable Entity
with error details500 Internal Server Error
with error messageCheck Infobip dashboard:
Test error scenarios:
Deploying your Node.js SMS service
Deploy your SMS service to a production environment:
Environment variables:
INFOBIP_BASE_URL
andINFOBIP_API_KEY
in your hosting environmentPORT
if needed (default: 3000)NODE_ENV=production
for production deploymentsHosting options:
Production checklist:
Frequently asked questions
How do I get an Infobip API key? Log into the Infobip Portal, navigate to the "Developers" section or account settings, and create a new API key. Copy the key immediately as you cannot view it again after creation.
What phone number format does Infobip require? Infobip requires phone numbers in international E.164 format without the
+
prefix (e.g.,447123456789
for a UK number). Use thelibphonenumber-js
library to validate and format phone numbers correctly.How much does it cost to send SMS via Infobip? SMS costs vary by destination country and message type. Check the Infobip pricing page or your account dashboard for current rates. Most countries charge per message segment (160 characters for GSM-7 encoding).
Can I send SMS to any country? Infobip supports SMS delivery to 190+ countries, but some countries have restrictions or require sender ID registration. Check Infobip's country-specific documentation for regulatory requirements.
How do I handle SMS delivery failures? Check the
status
field in the Infobip API response. Common failure reasons include invalid phone numbers, insufficient account balance, or carrier rejections. Implement webhook handlers to receive delivery reports for message status updates.What's the difference between sender ID and short code? A sender ID is an alphanumeric identifier (up to 11 characters) that appears as the message sender. A short code is a 5-6 digit number used primarily in the US for high-volume messaging. Sender ID availability and registration requirements vary by country.
How do I implement SMS opt-out compliance? Store opt-out requests in your database and check before sending. Include unsubscribe instructions in marketing messages (e.g., "Reply STOP to unsubscribe"). Process opt-out keywords automatically by implementing Infobip webhooks for incoming messages.
Can I schedule SMS messages for later delivery? Yes, use the
sendAt
parameter in the Infobip API payload to schedule messages. Pass an ISO 8601 timestamp for the desired delivery time. Note that scheduling is subject to Infobip's scheduling limits.Next steps for your SMS service
Enhance your SMS service with these features: