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.
This guide provides a step-by-step walkthrough for building a simple Node.js application using the Express framework to send SMS messages via the Infobip API. We'll cover project setup, core implementation, API key management, basic error handling, and testing.
By the end of this tutorial, you will have a functional Express API endpoint that accepts a phone number and message text, then uses the Infobip API to dispatch the SMS. This serves as a foundational building block for integrating SMS functionality into larger applications for notifications, alerts, or user communication.
Project Overview and Goals
.env
file. Chosen for securely managing API keys and configuration.POST /api/v1/sms/send
) that triggers an SMS message via Infobip.nvm
) to manage Node.js versions).1. Setting up the Project
Let's initialize our 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 Node.js Project: Run
npm init
to create apackage.json
file. You can accept the defaults by adding the-y
flag.This creates a
package.json
file which tracks your project's metadata and dependencies.Install Dependencies: We need
express
for the web server,axios
to make HTTP requests, anddotenv
to handle environment variables.This command downloads and installs the packages, adding them to your
node_modules
directory and listing them as dependencies inpackage.json
.Set up Project Structure: Create the following directory structure within
infobip-sms-sender
:src/
: Contains our application source code.controllers/
: Handles incoming requests and orchestrates responses.routes/
: Defines API endpoints and maps them to controllers.services/
: Contains business logic, like interacting with the Infobip API..env
: Stores environment variables (API keys, configuration). Never commit this file to version control..gitignore
: Specifies intentionally untracked files that Git should ignore (likenode_modules
and.env
).app.js
: The main entry point for our Express application.Configure
.gitignore
: Create a file named.gitignore
in the project root and add the following lines to prevent sensitive information and unnecessary files from being committed to Git:Configure Environment Variables (
.env
): Create a file named.env
in the project root. You'll need your Infobip API Key and Base URL.youruniqueid.api.infobip.com
.Add the following lines to your
.env
file, replacing the placeholder values with your actual credentials:INFOBIP_API_KEY
: Your secret API key for authenticating with Infobip.INFOBIP_BASE_URL
: The specific domain provided by Infobip for accessing their API.PORT
: The port number on which your Express server will listen.Why
.env
? Storing configuration like API keys directly in code is insecure and makes deployment difficult. Environment variables allow you to configure the application differently for development, testing, and production without changing the code.dotenv
loads these variables intoprocess.env
for easy access within your Node.js application.2. Implementing Core Functionality (Infobip Service)
Now, let's create the service responsible for interacting with the Infobip API. This logic is adapted from the Infobip developer blog post.
Create
src/services/infobipService.js
: This file will contain the functions to build the request and call the Infobip API.async/await
? It makes handling asynchronous operations (like theaxios.post
call) much cleaner and easier to read than traditional Promise.then()
and.catch()
chains.buildUrl
,buildHeaders
,buildRequestBody
,parseSuccessResponse
,parseFailedResponse
) improves code readability, maintainability, and testability.process.env
: The service directly accesses the API key and base URL from environment variables loaded bydotenv
, ensuring credentials aren't hardcoded.3. Building the API Layer (Routes and Controller)
Now, let's define the Express route and controller that will receive incoming requests and use our
infobipService
.Create
src/controllers/smsController.js
: This controller handles the request logic.to
andtext
fields are present in the request body. Production applications should implement more robust validation (e.g., using libraries likejoi
orexpress-validator
). The example includes a basic regex check for theto
field format and logs a warning for potential issues; for production, you should implement more robust validation and likely uncomment the provided code (or use a library) to reject formats known to be invalid according to Infobip requirements (international format without leading '+').sendSms
function from ourinfobipService
.Create
src/routes/smsRoutes.js
: This file defines the API endpoint.smsController
.POST
route at/send
(which will be prefixed later) and maps it to thehandleSendSms
controller function.Set up the Main Application File (
app.js
): This file initializes Express, loads environment variables, sets up middleware, and mounts the routes.dotenv.config()
: Loads variables from.env
intoprocess.env
. Crucially, this should be called before accessingprocess.env
variables (like ininfobipService.js
).express.json()
: Middleware to parse incoming requests with JSON payloads (available underreq.body
).smsRoutes
are mounted under the/api/v1/sms
path. This means the final endpoint URL will behttp://localhost:3000/api/v1/sms/send
. Versioning API paths (/v1/
) is a good practice./health
endpoint is included, useful for monitoring.4. Integrating with Infobip (Configuration Recap)
The core integration happens within
src/services/infobipService.js
using the credentials stored in.env
..env
: StoresINFOBIP_API_KEY
andINFOBIP_BASE_URL
.process.env.INFOBIP_API_KEY
..env
is included in.gitignore
to prevent accidental commits..env
file.INFOBIP_API_KEY
: (String, Required) Your unique secret key provided by Infobip. Used in theAuthorization: App <key>
header for authentication. Obtain from Infobip dashboard.INFOBIP_BASE_URL
: (String, Required) The specific domain assigned to your Infobip account (e.g.,xyz123.api.infobip.com
). Used to construct the target API endpoint URL. Obtain from Infobip dashboard.PORT
: (Number, Optional, Default: 3000) The port your local Node.js server will run on.(Note: For this basic example, no specific dashboard configurations beyond obtaining the API Key/Base URL are typically required for simple SMS sending. Fallback mechanisms are not implemented here but could involve trying alternative providers or queuing messages if Infobip is down).
5. Implementing Error Handling and Logging
Error handling is built into the service and controller:
infobipService
usestry...catch
around theaxios
call.parseFailedResponse
to create a standardized error object, whether it's an API error (4xx/5xx) or a network error.smsController
usestry...catch
to catch errors thrown by the service.statusCode
anderrorMessage
) to send an appropriate HTTP status code and JSON response to the client.console.log
andconsole.error
are used for logging requests and errors.app.js
.infobipService.js
.Winston
orPino
for structured logging, different log levels (debug, info, warn, error), and routing logs to files or external services.)429 Too Many Requests
), you could implement retries with exponential backoff using libraries likeaxios-retry
or manually within the service layer.)INFOBIP_API_KEY
in.env
to an incorrect value and send a request. Expect a401 Unauthorized
error response.INFOBIP_BASE_URL
to a non-existent domain. Expect a network error (likelyENOTFOUND
or timeout).to
ortext
in the body. Expect a400 Bad Request
response from the controller's validation.to
value (e.g.,'abcde'
) might result in an error from Infobip (often a400 Bad Request
indicating an invalid destination address).6. Database Schema and Data Layer
This specific example focuses solely on sending an SMS and does not require or include a database.
messageId
,status
,timestamp
).Prisma
,Sequelize
, orMongoose
. You would define schemas, handle migrations, and create data access functions within the service layer or a dedicated data layer.)7. Adding Security Features
Basic security is considered, but production systems require more.
.env
and.gitignore
. Crucial.to
,text
) are insmsController.js
. The controller also includes a basic warning for potentially invalid phone number formats.joi
orexpress-validator
for stricter schema validation, type checking, format validation (e.g., regex for phone numbers), and length limits. Ensure phone numbers strictly adhere to the expected international format before sending to Infobip.)DOMPurify
(for HTML) or custom logic might be needed if user input could be rendered elsewhere.)express-rate-limit
middleware to limit requests per IP address or user.)JWT
tokens, or other authentication methods.Nginx
orCaddy
) configured forHTTPS
, or use platform services (like Heroku, Render) that handle TLS termination. Do not handleTLS
directly in Node.js unless necessary.npm audit
).8. Handling Special Cases
15551234567
for US,447911123456
for UK). The code includes a basic check/warning but doesn't enforce strict formatting or reject invalid formats by default. Production apps often need pre-processing or libraries (like Google'slibphonenumber
) to validate and format numbers correctly before sending.GSM-7
encoding, fewer forUCS-2
used for non-Latin characters). Infobip handles concatenation for longer messages, but billing might be per segment. Be mindful of message length. This example doesn't explicitly handle encoding or splitting.from
field in the Infobip payload allows specifying a sender ID (alphanumeric string or phone number). This often requires pre-registration and approval with Infobip, especially for alphanumeric IDs. The example code comments out thefrom
field.smsController
.9. Implementing Performance Optimizations
For this simple, single API call per request, performance bottlenecks are unlikely within the Node.js application itself. The main latency will be the network round-trip to the Infobip API.
axios
(and Node.js's underlying HTTP agent) handles connection pooling/reuse automatically, which is the primary optimization here.10. Adding Monitoring, Observability, and Analytics
Basic logging is included. Production systems need more robust monitoring.
/health
endpoint provides a basic check.console.log
/console.error
provide minimal visibility.Winston
/Pino
) sending logs to services likeDatadog
,Logz.io
, orELK
stack for aggregation and analysis.)prom-client
for Prometheus metrics or integrate withAPM
(Application Performance Monitoring) tools likeDatadog APM
,New Relic
, orDynatrace
. These tools automatically instrument Express and Axios calls.)Sentry
orBugsnag
to capture errors in real-time with stack traces and context.)Grafana
(withPrometheus
),Datadog
, orNew Relic
are commonly used.11. Troubleshooting and Caveats
401 Unauthorized
(from Infobip): IncorrectINFOBIP_API_KEY
. Double-check the key in.env
and the Infobip dashboard.Network Error
/ENOTFOUND
/ECONNREFUSED
/ Timeout: IncorrectINFOBIP_BASE_URL
, DNS issues, firewall blocking outgoing connections, or Infobip API temporary unavailability. Verify the Base URL and network connectivity from the server.400 Bad Request
(from Infobip): Often indicates invalid input. Check:to
number format (should be international).axios
.from
sender ID (if used).details
field in the error response for specific Infobip error codes/messages (e.g.,Invalid destination address
).TypeError: Cannot read property '...' of undefined
(in Node.js): Often due to missing environment variables (dotenv.config()
not called early enough, variables missing in.env
) or unexpected response structures from Infobip. Add logging to trace variable values.