Frequently Asked Questions
Create a Fastify server with a POST /send-mms route, use the Infobip SDK to format the MMS message, and send it via the Infobip API. The request body should contain recipient, sender, media URL, and an optional caption. Ensure your Infobip account and sender number are MMS-enabled.
The Infobip Node.js SDK (`@infobip-api/sdk`) simplifies interaction with the Infobip API, offering convenient methods for sending SMS, MMS, and other communication types. It handles authentication, request formatting, and response parsing, making integration smoother.
Fastify is a high-performance Node.js web framework known for its speed and extensibility. Its schema validation feature helps ensure data integrity and security when handling incoming MMS requests. It's an excellent choice for building robust and efficient API endpoints.
Check your Infobip API key and base URL during server startup. This prevents the application from launching if critical credentials are missing. In server.js, verify these environment variables before initializing Fastify or requiring any services.
Dotenv loads environment variables from a .env file into process.env during development. This keeps sensitive API credentials out of your codebase and allows easy configuration changes without modifying core application files. Never commit .env to version control.
Implement a try-catch block in your service function and route handler. Catch errors originating from the Infobip API call, log detailed error messages including status codes, and return a user-friendly error response to the client. Check Infobip error codes for specific issues.
The Infobip MMS API requires a specific JSON structure for sending MMS messages, typically including an array called "messages", even for single MMS sends. Each message object needs recipient ('to'), sender ('from'), content object with media URL ('mediaUrl'), and an optional caption ('caption').
Phone numbers must be in E.164 format, e.g., +14155552671 (+ followed by country code and number). Validate phone numbers using the E.164 pattern (^\+[1-9]\d{1,14}$) during schema validation in your API endpoint. This prevents sending requests with invalid numbers.
No, the media URL for MMS messages must be publicly accessible without authentication. Infobip servers must be able to fetch the media directly from the URL. Internal network or private URLs will cause errors.
Create a directory for your project, initialize npm, install Fastify, the Infobip SDK, and dotenv. Create separate files for server logic (server.js), service functions (e.g., services/infobipService.js), and environment variables (.env, .env.example, .gitignore).
Use a plugin like fastify-rate-limit. Register the plugin in your server.js before your API routes. Configure limits like max requests per IP within a time window to prevent abuse and maintain a healthy system load.
Deploy your application to PaaS services like Heroku or Render via Git. For containerized deployments, build a Docker image using a Dockerfile. For serverless, adapt your app for platforms like AWS Lambda or Google Cloud Functions.
Input validation, through Fastify's JSON schema, prevents malformed data, potential injection attacks, and improves the robustness of your application. Using Fastify's schema, you can enforce required fields and specific data types, ensuring the validity of incoming requests.
Use environment variables for API keys and secrets. Implement input validation with Fastify's schema validation. Use rate limiting (e.g., fastify-rate-limit) to prevent abuse. Set secure HTTP headers with fastify-helmet. Run the application over HTTPS in production.
Send Infobip MMS with Fastify and Node.js: A Developer Guide
This guide provides a complete walkthrough for building a Node.js application using the Fastify framework to send Multimedia Messaging Service (MMS) messages via the Infobip API. We'll cover everything from project setup and configuration to core implementation, error handling, and deployment considerations.
By the end of this tutorial, you will have a functional Fastify API endpoint capable of accepting MMS details (recipient, sender, media URL, caption) and relaying them through Infobip for delivery. This solves the common need to integrate rich media messaging into applications programmatically.
Project Overview and Goals
@infobip-api/sdk
: The official Infobip Node.js SDK, simplifying interaction with their API.dotenv
: For managing environment variables securely.POST /send-mms
endpoint that takes JSON payload and sends an MMS message using credentials stored in environment variables.System Architecture:
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_ then navigate into it.
Initialize Node.js Project: Initialize the project using npm. The
-y
flag accepts the default settings.This creates a
package.json
file.Install Dependencies: We need Fastify for the web server_ the Infobip SDK to interact with their API_ and
dotenv
to manage environment variables.Create Project Structure: Set up a basic directory structure for organization:
Configure
.gitignore
: Create a.gitignore
file in the project root and addnode_modules
and.env
to prevent committing them to version control.Set up Environment Variables: Create two files in the root directory:
.env
(for your actual secrets) and.env.example
(as a template)..env.example
:.env
: Copy.env.example
to.env
and replace the placeholder values with your actual Infobip API Key and Base URL obtained from your Infobip dashboard. Set the desired port.dotenv
loads these variables intoprocess.env
for easy access in your Node.js application during development.2. Implementing Core Functionality (Infobip Service)
Now_ let's create the service module responsible for handling communication with the Infobip API using their SDK.
Create
infobipService.js
: Inside theservices
directory_ create theinfobipService.js
file.Implement the Service: Add the following code to
services/infobipService.js
.Infobip
client andAuthType
enum from the SDK.infobip
client instance using the API Key and Base URL loaded fromprocess.env
. We explicitly state we're usingAuthType.ApiKey
.sendMms
function takes the necessary parameters (to
,from
,mediaUrl
,caption
).mmsPayload
object matching the structure potentially expected by the Infobip MMS API (e.g.,/mms/1/single
or similar, often requiring amessages
array). Consult the latest Infobip MMS API documentation for the exact payload fields and structure.try...catch
block to handle potential errors during the API call.infobip.channels.mms.send(...)
is the presumed SDK method to send the message. Note: Verify the exact method name and required payload structure in the current@infobip-api/sdk
documentation.3. Building the API Layer (Fastify Server and Route)
Now, let's set up the Fastify server and create the API endpoint that will use our
infobipService
.Create
server.js
: In the project root, create theserver.js
file.Implement the Fastify Server: Add the following code to
server.js
:require('dotenv').config();
at the very top.INFOBIP_API_KEY
andINFOBIP_BASE_URL
is added before initializing Fastify or requiring the service, causing the app to exit if they are missing.pino-pretty
for development logging readability (install it withnpm install --save-dev pino-pretty
). Production uses standard JSON logging.infobipService
is imported after the environment variable check.GET /
route is added for health checks.sendMmsSchema
is defined using Fastify's schema validation. This ensures incoming requests have the required fields (to
,from
,mediaUrl
), checks their types and formats (URL, E.164 phone number pattern:`^\\+[1-9]\\d{1,14}$`
), and disallows extra properties. This provides input validation and security.POST /send-mms
route is defined:sendMmsSchema
for automatic request validation. If validation fails, Fastify automatically sends a 400 Bad Request response.request.body
.infobipService.sendMms
within atry...catch
block.start
function listens on the configured port (from.env
or default 3000) and handles server startup errors. Note the use ofparseInt(port, 10)
for the port number.Add Start Script: Modify your
package.json
to include start scripts.npm start
: Runs the server normally (intended for production, uses JSON logging).npm run dev
: Runs the server using Node's watch mode (restarts on file changes) and pipes logs throughpino-pretty
for better readability during development. Requiresnpm install --save-dev pino-pretty
.4. Integrating with Third-Party Services (Infobip Configuration Recap)
We've already integrated the core service, but let's recap the configuration points:
INFOBIP_API_KEY
: Obtain this from the Infobip Portal (usually under API Keys). It's used for authentication.INFOBIP_BASE_URL
: Your unique API endpoint URL provided by Infobip (e.g.,xxxxx.api.infobip.com
). This directs the SDK to the correct API server..env
file locally and use environment variables in your deployment environment. Never commit your.env
file or hardcode credentials directly in the source code.from
): Thefrom
number used in the API call must be an MMS-enabled number registered in your Infobip account and authorized for sending.mediaUrl
): The URL must be publicly accessible without authentication for Infobip's servers to fetch the media file. Ensure the URL points directly to the image file (JPEG, PNG, etc.).5. Error Handling, Logging, and Retries
infobipService
catches errors during the API call (e.g., network issues, invalid credentials, Infobip API errors). It logs detailed error information and throws a generic error upwards.POST /send-mms
route catches errors from the service layer and returns a standardized error response to the client (e.g., 500 Internal Server Error).request.log
) is used for request-related logging.console.log/error
is used for startup messages/errors.LOG_LEVEL
environment variable. Useinfo
for production,debug
ortrace
for development/troubleshooting.pino-pretty
enhances log readability during development. In production, use structured JSON logging (Fastify's default withoutpino-pretty
) for easier analysis by log aggregation tools.async-retry
can simplify this. Wrap theinfobipService.sendMms
call or the SDK call within a retry function.6. Database Schema and Data Layer (Not Applicable)
This specific guide focuses solely on the API interaction and doesn't require a database. If you needed to store message history, track statuses via webhooks, or manage user data, you would introduce a database (e.g., PostgreSQL, MongoDB) and a data access layer (e.g., using an ORM like Prisma or Sequelize).
7. Security Features
Input Validation: Handled by Fastify's schema validation (
sendMmsSchema
), preventing malformed data and basic injection attempts. The E.164 pattern (`^\\+[1-9]\\d{1,14}$`
) enforces a specific format.additionalProperties: false
prevents unexpected data.Secret Management: API keys and sensitive configuration are managed via environment variables (
.env
locally, platform environment variables in production)..gitignore
prevents accidental commits.Rate Limiting: Protect your API from abuse. Use a plugin like
@fastify/rate-limit
.HTTPS: Ensure your deployed application runs over HTTPS to encrypt communication. This is typically handled by your hosting provider or load balancer (reverse proxy).
Helmet: Set various security-related HTTP headers using
@fastify/helmet
.8. Handling Special Cases
+14155552671
). The schema validates this format using the regex`^\\+[1-9]\\d{1,14}$`
. More complex validation might be needed depending on specific regional requirements or if you need to normalize different input formats.mediaUrl
must be public and directly accessible. Internal or authenticated URLs will cause Infobip to fail fetching the media, resulting in an error.error.response.data
from the SDK error to map these to more user-friendly error messages or trigger specific alerts.9. Performance Optimizations (Considerations)
k6
,autocannon
, orwrk
to test the endpoint's performance under load, especially if high throughput is expected. Identify bottlenecks (CPU, memory, network latency to Infobip).10. Monitoring, Observability, and Analytics (Considerations)
GET /
route provides a basic health check. More sophisticated checks could verify connectivity to Infobip (e.g., by making a low-impact, authenticated API call like fetching account balance, if available).fastify-metrics
, Datadog). Track request rates, error rates (HTTP 4xx/5xx), latency (overall API response time and specifically the latency of theinfobipService.sendMms
call).@sentry/node
) or Datadog APM to capture and aggregate errors in production, providing stack traces and context for easier debugging.notifyUrl
parameter in the payload) to track message delivery status and analytics directly from Infobip.11. Troubleshooting and Caveats
Invalid login details
Error (from Infobip):INFOBIP_API_KEY
orINFOBIP_BASE_URL
..env
file (or deployment environment variables) against the Infobip portal. Ensure the Base URL is correct for your account region and API key type.Failed to fetch media
Error (or similar):mediaUrl
provided is not publicly accessible, points to a non-media file, is malformed, the hosting server blocked Infobip's request (e.g., firewall, User-Agent block), or the URL timed out.curl
. Ensure it links directly to the image. Check your media server logs if you host the media. Ensure the media type is supported by Infobip MMS.Invalid ""To"" address
Error:to
) is not in valid E.164 format (+
followed by country code and number, e.g.,+14155552671
), is invalid for the destination country, or is on a blacklist.Message sending not enabled for number
Error:from
number is not configured or approved for sending MMS in your Infobip account, or MMS sending is not enabled for the specific destination country/carrier.@infobip-api/sdk
with your Node.js version. Check the SDK's documentation orpackage.json
for requirements. Method calls (likeinfobip.channels.mms.send
) and payload structures might change between major SDK versions. Always refer to the specific SDK version documentation you are using.12. Deployment and CI/CD
Environment Configuration: Do not deploy your
.env
file. ConfigureINFOBIP_API_KEY
,INFOBIP_BASE_URL
,PORT
,LOG_LEVEL
, andNODE_ENV=production
using your deployment platform's environment variable management system (e.g., Heroku Config Vars, AWS System Manager Parameter Store, Kubernetes Secrets, Docker environment variables).Deployment Platforms:
package.json
specifies the correct Node.js engine.Dockerfile
to package your application. Manage containers using Docker Compose (for simple setups), Kubernetes, or managed services like AWS ECS/Fargate, Google Cloud Run.aws-lambda-fastify
or@fastify/aws-lambda
, or potentially restructure as individual functions triggered by API Gateway.Dockerfile
Example:CI/CD Pipeline (e.g., GitHub Actions, GitLab CI, Jenkins):
npm ci
oryarn install --frozen-lockfile
.npm run lint
- requires adding a lint script).npm test
). Ensure tests cover validation, service logic (mocked), and route handling.npm audit
, Snyk).Rollback Strategy: Ensure your deployment process allows for easy rollback to a previous stable version in case of deployment failures or runtime issues in the new version.
13. Verification and Testing
Ensure your
.env
file has correct credentials and a valid publicmediaUrl
.Start the server:
npm run dev
(for pretty logs) ornpm start
.Use
curl
or a tool like Postman/Insomnia to send a POST request tohttp://localhost:3000/send-mms
(or your configured port).curl
Example:+1xxxxxxxxxx
with your actual recipient phone number (must be allowed by your Infobip account, e.g., your registered number on a free trial).+1yyyyyyyyyy
with your valid, MMS-enabled Infobip sender number.mediaUrl
with a working, publicly accessible image URL (e.g.,https://placehold.co/600x400.png
).