Frequently Asked Questions
This guide details setting up a Node.js application with Express to send SMS messages using the Infobip API. It covers project setup, API integration, error handling, and testing. You'll create an API endpoint that accepts a phone number and message, then dispatches the SMS via Infobip.
The Infobip API is a third-party service used in this tutorial to send SMS messages programmatically. It handles the actual delivery of the SMS to the recipient's phone number. This automation is useful for transactional messages, alerts, and user communication within applications.
Express.js simplifies the process of building a web server and API endpoints in Node.js. Its minimal structure and routing capabilities make it ideal for creating the SMS sending endpoint required in this tutorial.
Phone number validation should occur before sending any SMS via the Infobip API. The controller in this example performs a basic check but stricter format validation is recommended. It's crucial for preventing errors and ensuring deliverability, especially when using international numbers.
Yes, you can use an Infobip free trial account, but it has limitations. Testing is typically restricted to sending SMS messages only to the phone number verified during signup. Other numbers will likely fail until you upgrade to a paid account.
Create a .env
file in your project's root directory. Add your INFOBIP_API_KEY
and INFOBIP_BASE_URL
obtained from your Infobip account dashboard. The dotenv
package loads these variables into process.env
for secure access within your Node.js application.
Axios is a promise-based HTTP client used to make requests to the Infobip API. It simplifies sending the POST request with the recipient's number and message text to trigger the SMS sending process. The example code demonstrates how to use axios and parse responses.
Error handling involves using try...catch
blocks around the API call with axios
within the infobipService
and controller. The parseFailedResponse
function helps standardize error objects, and you can add logging and retry mechanisms. The example includes basic error parsing and response handling.
This tutorial focuses on demonstrating a simple, stateless SMS sending function where incoming requests are handled directly via the Infobip API. A database isn't needed to store application state or message details, reducing complexity for the basic example.
The tutorial recommends a structure with controllers
, routes
, and services
directories within a src
folder. Controllers manage requests, routes define API endpoints, and services encapsulate the Infobip API interaction logic.
You need Node.js and npm (or yarn) installed, an active Infobip account, and basic understanding of JavaScript, Node.js, REST APIs, and command-line usage. Familiarity with environment variables and asynchronous operations is also beneficial.
After setting up the project and configuring your .env
file, you can test by sending a POST request to the /api/v1/sms/send
endpoint with a valid phone number and message text in the request body. Tools like Postman or curl can be used to make these test requests.
Protecting your API key is critical. The .env
file keeps it out of version control. Input validation is essential to prevent issues and robust phone number formatting is recommended. Additional security measures like rate limiting and HTTPS in production are important considerations.
Log in to your Infobip account portal and navigate to the main dashboard or homepage. Your unique API Key and Base URL will be displayed there. Copy these values into the .env
file in your project.
Send SMS with Node.js and Express: Infobip API Integration Tutorial
Build a Node.js application using Express to send SMS messages via the Infobip API. This tutorial covers project setup, implementation, API key management, error handling, and testing.
You'll create a functional Express API endpoint that accepts a phone number and message text, then dispatches the SMS through Infobip. Use this as a foundation for integrating SMS functionality into larger applications.
Project Overview and Goals
.env
files. Chosen for secure API key management.POST /api/v1/sms/send
that triggers SMS delivery via Infobip.nvm
) to manage versions.Setting Up Your Node.js SMS Project
Initialize your Node.js project and install dependencies.
Create Project Directory: Open your terminal and create a new directory. Navigate into it.
Initialize Node.js Project: Run
npm init
to createpackage.json
. Accept defaults with the-y
flag.This creates
package.json
, which tracks project metadata and dependencies.Install Dependencies: Install
express
for the web server,axios
for HTTP requests, anddotenv
for environment variables.This downloads packages to
node_modules
and lists them inpackage.json
.Set up Project Structure: Create this directory structure within
infobip-sms-sender
:src/
: Application source code.controllers/
: Handles incoming requests and orchestrates responses.routes/
: Defines API endpoints and maps them to controllers.services/
: Business logic for interacting with the Infobip API..env
: Stores environment variables (API keys, configuration). Never commit this file..gitignore
: Specifies files Git should ignore (node_modules
,.env
).app.js
: Main entry point for the Express application.Configure
.gitignore
: Create.gitignore
in the project root:Configure Environment Variables (
.env
): Create.env
in the project root. You need your Infobip API Key and Base URL.youruniqueid.api.infobip.com
).Add these lines to
.env
, replacing placeholders with your credentials:INFOBIP_API_KEY
: Your secret API key for Infobip authentication.INFOBIP_BASE_URL
: Your account-specific domain for API access.PORT
: Port number for your Express server.Why
.env
? Storing API keys in code is insecure and complicates deployment. Environment variables let you configure applications differently across environments (development, testing, production) without code changes.dotenv
loads these intoprocess.env
.Building the Infobip SMS Service Layer
Create the service that interacts with the Infobip API. This logic adapts the Infobip developer blog post.
Create
src/services/infobipService.js
: This file builds requests and calls the Infobip API.async/await
: Makes asynchronous operations cleaner than Promise chains.buildUrl
,buildHeaders
,buildRequestBody
,parseSuccessResponse
,parseFailedResponse
improves readability, maintainability, and testability.Creating the Express API Routes and Controller
Define the Express route and controller that receives requests and uses
infobipService
.Create
src/controllers/smsController.js
: This controller handles request logic.Create
src/routes/smsRoutes.js
: This file defines the API endpoint.Set up the Main Application File (
app.js
): Initialize Express, load environment variables, configure middleware, and mount routes.dotenv.config()
: Loads.env
variables intoprocess.env
before accessing them.express.json()
: Parses incoming JSON payloads (available viareq.body
).smsRoutes
under/api/v1/sms
, creating final endpointhttp://localhost:3000/api/v1/sms/send
./health
endpoint for monitoring.Configuring Infobip API Credentials
Integration happens in
src/services/infobipService.js
using credentials from.env
..env
: StoresINFOBIP_API_KEY
andINFOBIP_BASE_URL
.process.env.INFOBIP_API_KEY
..env
in.gitignore
to prevent commits..env
file.INFOBIP_API_KEY
: (String, Required) Your unique secret key from Infobip. Used inAuthorization: App <key>
header.INFOBIP_BASE_URL
: (String, Required) Your account-specific domain (e.g.,xyz123.api.infobip.com
). Used to construct API endpoint URLs.PORT
: (Number, Optional, Default: 3000) Your local server port.Error Handling and Logging Best Practices
Error handling is built into the service and controller:
infobipService
usestry...catch
aroundaxios
calls.parseFailedResponse
to create standardized error objects for API errors (4xx/5xx) or network errors.smsController
catches errors and inspectsstatusCode
anderrorMessage
to return appropriate HTTP responses.console.log
andconsole.error
for basic logging.app.js
.infobipService.js
.Winston
orPino
for structured logging with different levels and external service routing.429 Too Many Requests
), implement retries with exponential backoff usingaxios-retry
or custom logic.INFOBIP_API_KEY
in.env
to incorrect value. Expect401 Unauthorized
.INFOBIP_BASE_URL
to non-existent domain. Expect network error (ENOTFOUND
or timeout).to
ortext
. Expect400 Bad Request
.to
value (e.g.,'abcde'
). Expect400 Bad Request
from controller validation.Security Best Practices for SMS APIs
Basic security is included; production systems need more.
.env
and.gitignore
. Critical.smsController.js
.joi
orexpress-validator
for schema validation, type checking, and length limits.express-rate-limit
middleware to limit requests per IP or user.Nginx
,Caddy
) configured for HTTPS, or use platforms (Heroku, Render) handling TLS termination.npm audit
).Understanding SMS Format Requirements and Limitations
15551234567
for US,447911123456
for UK). Enhanced validation enforces 7-15 digit format. Production apps should uselibphonenumber
for robust validation and formatting.from
field in the Infobip payload specifies sender ID (alphanumeric or phone number). Requires pre-registration and approval with Infobip. The example code comments outfrom
.Performance Optimization for High-Volume SMS
For simple, single API calls per request, performance bottlenecks are unlikely. Main latency is network round-trip to Infobip.
axios
and Node.js HTTP agent handle connection pooling/reuse automatically.Monitoring Your Node.js SMS Application
Basic logging is included. Production systems need robust monitoring.
/health
endpoint provides basic status.console.log
/console.error
provide minimal visibility.Winston
/Pino
for structured logging toDatadog
,Logz.io
, or ELK stack.prom-client
for Prometheus metrics or integrate APM tools (Datadog APM
,New Relic
,Dynatrace
).Sentry
orBugsnag
for real-time error capture with stack traces.Grafana
withPrometheus
,Datadog
, orNew Relic
.Troubleshooting and Caveats
401 Unauthorized
(from Infobip): IncorrectINFOBIP_API_KEY
. Verify key in.env
and Infobip dashboard.Network Error
/ENOTFOUND
/ECONNREFUSED
/Timeout: IncorrectINFOBIP_BASE_URL
, DNS issues, firewall blocking outgoing connections, or temporary Infobip unavailability. Verify Base URL and network connectivity.400 Bad Request
(from Infobip): Invalid input. Check:to
number format (must be E.164: 7-15 digits, no '+').from
sender ID (if used).details
field in error response for specific Infobip error codes (e.g.,Invalid destination address
).TypeError: Cannot read property '...' of undefined
: Missing environment variables (dotenv.config()
not called early, variables missing in.env
) or unexpected Infobip response structures. Add logging to trace variable values.Frequently Asked Questions (FAQ)
Q: What Node.js versions are compatible with Infobip? A: Node.js v18.x or v20.x LTS versions are recommended. Earlier versions may work but lack current security patches and performance improvements.
Q: Do I need a paid Infobip account to send SMS? A: Free trial accounts can send SMS to verified phone numbers only. For production use or testing with multiple numbers, you'll need to fund your account.
Q: What phone number format does Infobip require? A: Infobip requires E.164 international format: country code + national number, 7-15 digits total, without the '+' prefix. Example:
15551234567
(US) or447911123456
(UK).Q: How many characters can I send in one SMS? A: Standard SMS supports 160 characters (GSM-7 encoding) or 70 characters (UCS-2/Unicode for non-Latin scripts). Longer messages are automatically split into multiple segments, with separate billing per segment.
Q: How do I track SMS delivery status? A: Configure webhooks in the Infobip Portal to receive real-time delivery reports (DELIVERED, FAILED, etc.). The
messageId
returned from the send request can be used to query delivery status via Infobip's API.Q: Can I customize the sender ID for my SMS messages? A: Yes, use the
from
field in the message payload. Alphanumeric sender IDs require pre-registration and approval with Infobip. Some countries restrict sender ID customization.Q: How do I handle rate limits with Infobip? A: Implement rate limiting in your application using
express-rate-limit
. For transient rate limit errors (429 responses), add retry logic with exponential backoff using libraries likeaxios-retry
.Q: Is this code production-ready? A: This tutorial provides a foundation. For production, add: robust input validation (use
joi
orexpress-validator
), comprehensive error handling, retry mechanisms, structured logging (Winston
/Pino
), monitoring (Datadog
/New Relic
), rate limiting, and authentication/authorization.Q: How do I test my integration without sending real SMS? A: Use your verified trial phone number for testing, or upgrade to a paid account and use test numbers. Infobip also offers simulation modes in some regions—check their documentation.
Q: What's the typical latency for sending SMS through Infobip? A: Network latency to Infobip's API typically ranges from 200ms to 2 seconds depending on your location and network conditions. Actual SMS delivery to the recipient's device depends on carrier networks (usually 1-10 seconds).
Q: Can I send SMS to international numbers? A: Yes, Infobip supports international SMS delivery to 190+ countries. Ensure phone numbers are in proper E.164 format with the correct country code. Pricing varies by destination country.
Q: How do I handle special characters in SMS messages? A: GSM-7 encoding supports basic Latin characters and common symbols. For special characters (emojis, non-Latin scripts), messages use UCS-2 encoding, reducing the character limit to 70 per segment. Infobip handles encoding automatically based on message content.