Frequently Asked Questions
Use the Infobip API along with Express and Node.js. Create a REST API endpoint that accepts recipient details, message content, and a media URL, then uses the Infobip API to send the MMS message. This setup enables programmatic sending of MMS messages for various applications.
The Infobip API is the core service for sending MMS messages in this Node.js and Express application. It handles constructing the message with media and text and delivers it to the recipient's mobile carrier. The Node.js app acts as an intermediary to format requests and handle responses from the Infobip platform.
Infobip's MMS API expects data in the multipart/form-data format, which handles combining different data types, such as text, images, and other media, within a single HTTP request. This format is distinct from the JSON typically used for SMS messages and is crucial for sending rich media messages via Infobip.
Always use environment variables for sensitive information like API keys, and load them with dotenv during development. This keeps secrets out of your codebase and enhances security. In production, leverage your platform's secure mechanisms for managing environment variables.
While the Infobip API supports MMS messages up to 1MB, it's recommended to keep the media size under 300KB for reliable delivery. Large files might lead to delivery issues or timeouts. Optimize media for mobile devices to ensure efficient transmission.
Install necessary packages like Express, Axios, form-data, and dotenv. Set up project structure with appropriate routes, controllers, and services. Configure environment variables for credentials and server details. Implement Infobip service logic with error handling and response parsing.
Use the E.164 format (e.g., +12223334444) for recipient phone numbers. It ensures compatibility and accuracy in international MMS delivery. Use a library like libphonenumber-js to validate or format numbers consistently.
Retries handle transient failures like network issues or temporary Infobip API unavailability. The async-retry library, with exponential backoff, can be used for implementing retries in the axios.post call within the Infobip service logic.
Use Axios's `responseType: 'stream'` option to fetch media from the provided URL efficiently. This allows handling potentially large files without loading them fully into memory, leading to better performance, especially with larger files.
Input validation, secure API key storage, and rate limiting are crucial security aspects. Use tools like Joi for validation, dotenv and secure environment variable storage in production, and express-rate-limit to prevent abuse and protect your application.
Implement a central error handler in your server.js file that logs details and parses Infobip's error messages, enabling informed debugging and user-friendly error responses. The error details often give insights into the issue's root cause.
While Infobip technically supports larger lengths, for subject lines keep them under 50 characters and for text content under 500 characters is recommended. Use UTF-8 encoding for text to accommodate a wide range of characters.
Implement health checks, track metrics using Prometheus or APM tools, monitor Infobip API latency specifically, and integrate with error tracking solutions like Sentry or Bugsnag for real-time alerts and insights.
A database schema allows storing message logs, including recipient details, content, delivery status, and timestamps. This data can be used to track message history, resend failed messages, and generate reports.
Create a Dockerfile, build the image, and run the container, ensuring environment variables are configured securely through mechanisms like -e, --env-file, or Docker secrets, and that a process manager like PM2 is used in production.
Developer Guide: Sending MMS with Node.js, Express, and Infobip
This guide provides a step-by-step walkthrough for building a production-ready Node.js application using the Express framework to send Multimedia Messaging Service (MMS) messages via the Infobip API. We will cover project setup, core implementation, API creation, error handling, security, deployment, and verification.
Note: Some sections refer to external links or specific user credentials (like GitHub repository links, API keys, Docker Hub usernames). Where the actual link or value was not provided, placeholders remain. Please replace these placeholders with your actual values.
Project Overview and Goals
What We're Building:
We will create a simple REST API endpoint using Node.js and Express. This endpoint will accept requests containing recipient information, a subject, text content, and a URL pointing to media (like an image). It will then use the Infobip API to construct and send an MMS message including this text and media to the specified recipient.
Problem Solved:
This guide enables developers to programmatically send rich media messages (MMS) through a reliable provider like Infobip, integrating this capability into their applications for use cases such as marketing campaigns, notifications with images, or customer support involving visual aids.
Technologies Used:
multipart/form-data
streams, necessary for the Infobip MMS API..env
file.System Architecture:
Prerequisites:
Expected Outcome:
By the end of this guide, you will have a running Express application with a single API endpoint (
POST /send-mms
) that can successfully send an MMS message containing text and an image (fetched from a URL) via Infobip.1. Setting up the Project
Let's initialize our Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal and create a new directory for the project.
Initialize npm Project: Initialize the project using npm. The
-y
flag accepts the default settings.This creates a
package.json
file. Make sure it includes""type"": ""module""
to enable ES Module syntax (see Section 3).Install Dependencies: We need Express for the server, Axios for HTTP requests,
form-data
to construct the multipart request for Infobip's MMS API, anddotenv
to manage environment variables securely.Create Project Structure: Set up a basic directory structure for better organization.
Configure
.gitignore
: Prevent sensitive files and node modules from being committed to version control. Add the following to your.gitignore
file:Set up Environment Variables: Open the
.env
file and add your Infobip credentials and other configuration. Replace the placeholder values below with your actual credentials. Never commit this file to Git.INFOBIP_BASE_URL
: Replace with the Base URL from your Infobip account's homepage or API documentation section (e.g.,xxxxx.api.infobip.com
).INFOBIP_API_KEY
: Replace with the API key generated in the API key management section of your Infobip dashboard. Treat it like a password.SENDER_NUMBER
: Replace with the MMS-enabled phone number associated with your Infobip account that will appear as the sender. Ensure it's in E.164 format (e.g.,+12223334444
).PORT
: The port number on which your Express server will listen.2. Implementing Core Functionality (Infobip Service)
This service module will encapsulate the logic for interacting with the Infobip MMS API. The key difference from sending SMS is that MMS requires a
multipart/form-data
request structure.Open
src/services/infobipService.js
and add the following code:Why this approach?
multipart/form-data
: Infobip's MMS API requires this format, unlike the JSON typically used for SMS. Theform-data
library correctly structures the request.responseType: 'stream'
) and passing it directly into the form data is memory-efficient, especially for larger files. It avoids loading the entire media file into memory.head
,text
, andfile
parts as required by the Infobip MMS specification found in their documentation.form-data
generates the correctContent-Type
header with the boundary. We add theAuthorization
header using theApp
scheme as specified by Infobip.3. Building the API Layer (Express)
Now, let's create the Express route and controller to handle incoming requests and use our
infobipService
.Controller (
src/controllers/mmsController.js
):Routes (
src/routes/mmsRoutes.js
):Server Setup (
src/server.js
):Add Start Script and Ensure
type: module
inpackage.json
:Modify your
package.json
to include a start script and ensure""type"": ""module""
is present to enable ES Module syntax (import
/export
).Testing the API Endpoint:
Start the server:
Send a POST request using
curl
(or Postman/Insomnia): Remember to replace+1_REPLACE_WITH_RECIPIENT_NUMBER
with an actual E.164 formatted recipient phone number.Expected Response (Success):
Expected Response (Error - e.g., Invalid API Key):
4. Integrating with Infobip (Credentials & Setup)
xxxxx.api.infobip.com
..env
file loaded bydotenv
. This file is listed in.gitignore
to prevent accidental commits of your secret credentials. In production environments, use your hosting provider's mechanism for managing environment variables securely (e.g., AWS Secrets Manager, Heroku Config Vars, Docker Secrets)..env
Variables (Recap):INFOBIP_BASE_URL
: (String) Replace placeholder. Base domain for Infobip API calls.INFOBIP_API_KEY
: (String) Replace placeholder. Your secret API key.SENDER_NUMBER
: (String) Replace placeholder. Your MMS-capable number from Infobip (E.164 format).PORT
: (Number) Local port for the Express server.5. Error Handling, Logging, and Retry Mechanisms
infobipService.js
) throws errors for config issues, input validation, media fetching failures, and Infobip API errors (extracting status and data).mmsController.js
) performs input validation and catches errors, passing them vianext(error)
.server.js
) catches errors, logs them, attempts to parse Infobip details from the error message (usingerror.response
data if available via the service layer), and sends a structured JSON response.console.log
andconsole.error
.async-retry
around theaxios.post
call ininfobipService.js
. Use exponential backoff.messageId
from Infobip's response (if a partial failure occurred) or implement your own idempotency keys if needed.6. Database Schema and Data Layer (Optional)
While not required for basic sending, tracking message status often involves a database.
7. Security Features
joi
orexpress-validator
for more robust schema validation and sanitization in routes/controllers..env
(local) and secure environment variables (production). Never hardcode keys.express-rate-limit
to prevent abuse. Apply it before your API routes inserver.js
.helmet
middleware inserver.js
(app.use(helmet());
) to set security-related HTTP headers.8. Handling Special Cases
mediaUrl
points to suitable files.+1...
) expected. Uselibphonenumber-js
for robust validation/formatting if needed.SENDER_NUMBER
is correctly registered and provisioned for A2P MMS traffic if applicable.9. Implementing Performance Optimizations
axios
(responseType: 'stream'
) is key for memory efficiency.async/await
prevents blocking the Node.js event loop.mediaUrl
is reused often) is possible but adds complexity. Use in-memory (node-cache
) or external (Redis) caches.k6
_artillery
_autocannon
to test throughput and identify bottlenecks under load.clinic.js
to analyze CPU/memory usage.10. Adding Monitoring_ Observability_ and Analytics
/health
endpoint for basic checks. Enhance for production (check dependencies). Integrate with uptime monitors.prom-client
for Prometheus metrics (request latency_ rate_ errors) or integrate with APM tools. Monitor Infobip API call latency specifically. Track system metrics (CPU_ memory).11. Troubleshooting and Caveats
401 Unauthorized
(Infobip): CheckINFOBIP_API_KEY
andAuthorization: App <key>
format.400 Bad Request
(Infobip): Check recipient format (E.164), request structure, or Infobip's detailed error message.403 Forbidden
(Infobip): Check MMS enablement, free trial limits, A2P/10DLC compliance. Contact Infobip support if needed.Failed to fetch media...
: VerifymediaUrl
accessibility and correctness.ECONNREFUSED
/ENOTFOUND
: CheckINFOBIP_BASE_URL
, DNS, network connectivity.timeout: 60000
) cautiously.mms_log
table). ThebulkId
andmessageId
returned in the initial send response are key to correlating these updates.12. Deployment and CI/CD
.env
file in production), Install Prod Dependencies (npm ci --only=production
), Run with Process Manager (PM2), Setup Reverse Proxy (Nginx/Caddy for HTTPS, etc.).