Frequently Asked Questions
Use a Node.js web framework like Fastify and the MessageBird MMS API. Create an endpoint that handles MMS requests, including recipient numbers, message body, media URLs, and other parameters. Then, use a library like Axios to send the request to MessageBird's API.
Fastify is a high-performance web framework for Node.js known for its speed and developer-friendly experience. Its efficiency makes it suitable for handling API requests, like those required for sending MMS messages with MessageBird.
The article specifies that MessageBird's focus for MMS is the US and Canada. Ensure your recipients are in these regions. Check MessageBird's official documentation for the most up-to-date coverage information.
Use MMS when you need to send rich media content like images or short videos along with text. MMS is ideal for notifications, marketing campaigns, and user engagement that benefits from visual elements, primarily in the US and Canada.
The article primarily describes MMS functionality with MessageBird for the US and Canada. It does not cover international MMS. Consult MessageBird's documentation for their current international MMS capabilities if you need to send messages outside the US and Canada.
MessageBird requires public URLs for media files. Host your media on a publicly accessible service like AWS S3 or Cloudinary. Include an array of these URLs in the 'mediaUrls' field of your API request to MessageBird. Each file must be under 1MB, and you can include up to 10 URLs.
The 'originator' is your MMS-enabled virtual mobile number (VMN) purchased from MessageBird, formatted in E.164 (e.g., +12015550123). This number must be specifically enabled for MMS in your MessageBird settings and is the number messages appear to come from.
Store your MessageBird API key and other sensitive credentials as environment variables. Load them using the `dotenv` package in development, but use secure configuration management in production deployments. Never commit these keys directly to your code repository.
Axios is a promise-based HTTP client that simplifies making API requests. It's used in this example application to send POST requests containing the MMS payload (recipient, message, media URLs, etc.) to the MessageBird MMS API endpoint.
Configure a webhook URL in your MessageBird dashboard's number settings. MessageBird will send GET requests to this URL with status updates. In your application, create a route that handles these requests, logs the updates, and importantly, sends an immediate 200 OK response to acknowledge receipt.
Use a combination of unit tests (with mocking libraries like Nock) to test your application logic and integration tests (with tools like curl or Postman) to send real MMS messages to test numbers. Ensure your `.env` file is configured correctly and use test credentials if possible.
The `x-api-key` header provides an additional layer of security for *your* Fastify application's `/send-mms` endpoint. This prevents unauthorized access. The key is set in your `.env` file.
Choose a hosting provider like Heroku, AWS, Google Cloud, etc. Set environment variables securely on the platform, ensure `NODE_ENV` is set to 'production', and configure logging and a process manager. Containerization with Docker and Kubernetes or managed container services is also recommended.
Each individual media file included in your MMS message must be 1MB (1024KB) or less, according to the MessageBird API specifications.
You can include a maximum of 10 'mediaUrls' in a single MMS message request to the MessageBird API.
This guide provides a step-by-step walkthrough for building a robust Node.js application suitable for deployment using the Fastify framework to send Multimedia Messaging Service (MMS) messages via the MessageBird API. Note that MessageBird's MMS sending capabilities are primarily focused on the US and Canada.
We will build a simple API endpoint that accepts recipient information, message content (text and/or media URLs), and uses MessageBird to deliver the MMS. We will also cover essential aspects like configuration, error handling, security, receiving status updates, testing, and deployment.
Project Overview and Goals
Goal: Create a reliable and scalable service to send MMS messages programmatically.
Problem Solved: Automates the process of sending rich media messages (images, videos, etc.) to users in the US and Canada, enabling richer communication for notifications, marketing, or user engagement compared to SMS alone.
Technologies:
.env
file intoprocess.env
.System Architecture:
Prerequisites:
originator
number.Expected Outcome: A Fastify application with a secure endpoint (
/send-mms
) capable of accepting MMS requests and relaying them to the MessageBird API for delivery. The application will also have an endpoint (/mms-status
) to receive delivery status updates from MessageBird.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: This creates a
package.json
file.(Use
yarn init -y
if you prefer Yarn)Install Dependencies: We need Fastify for the web server,
axios
to call the MessageBird API, anddotenv
for managing environment variables.(Use
yarn add fastify axios dotenv
for Yarn)Install Development Dependencies:
pino-pretty
helps format logs nicely during development.(Use
yarn add --dev pino-pretty
for Yarn)Create Project Structure: Create the basic files and directories.
server.js
: Main application code..env
: Stores sensitive credentials (API keys, etc.). Do not commit this file..env.example
: A template showing required environment variables. Commit this file..gitignore
: Specifies files/directories Git should ignore.Configure
.gitignore
: Addnode_modules
and.env
to your.gitignore
file to prevent committing them.Set up
package.json
Scripts: Add scripts topackage.json
for easily running the application.npm start
: Runs the server in production mode (standard logs).npm run dev
: Runs the server with human-readable logs viapino-pretty
.2. Configuration
Securely managing credentials and settings is crucial. We'll use environment variables loaded via
dotenv
.Define Environment Variables (
.env.example
): List the required variables in.env.example
.Populate
.env
File: Create a.env
file (or copy.env.example
to.env
) and fill in the actual values:MESSAGEBIRD_API_KEY
: Your Live Access Key from the MessageBird Dashboard (Developers > API access).MESSAGEBIRD_ORIGINATOR
: Your MMS-enabled US or Canadian number purchased from MessageBird, in E.164 format (e.g.,+12015550123
). Crucially, this number must be explicitly enabled for MMS within your MessageBird settings.PORT
: The port your Fastify server will listen on (default: 3000).HOST
: The host address (default:0.0.0.0
to listen on all available network interfaces).FASTIFY_API_KEY
: A secret key you define. Clients calling your/send-mms
endpoint will need to provide this key for authentication. Generate a strong, random string for this.LOG_LEVEL
: Controls log verbosity (e.g.,info
,debug
,warn
,error
).Load Environment Variables in
server.js
: At the very top of yourserver.js
, load the variables.3. Implementing the MMS Sending Route
Now, let's build the core logic in
server.js
.Basic Fastify Server Setup: Initialize Fastify and configure basic logging.
Add Authentication Hook: We'll protect our
/send-mms
route using a simple API key check via a Fastify hook.Define the
/send-mms
Route: This route will handle POST requests to send MMS messages.Explanation:
recipient
/recipients
,body
/mediaUrls
), types, and constraints (lengths, max items) before our handler logic runs. It also specifies the expected success (200) and error (400, 401, 500, 503) response formats.anyOf
ensures eitherbody
ormediaUrls
is present.oneOf
ensures onlyrecipient
orrecipients
is used and that at least one is provided.preHandler: [fastify.authenticate]
: This applies our authentication hook to this specific route, handling potential 401 errors./mms
endpoint, using theoriginator
from environment variables and data from the incoming request. We clean up undefined or null optional fields. We add checks for recipient limits and presence (returning 400).axios.post
: We make the POST request to MessageBird's API endpoint.Authorization: AccessKey ...
header is crucial for authenticating with MessageBird.Content-Type: application/json
.axios
throws an error (network issue, non-2xx response from MessageBird), we catch it, log detailed information, determine an appropriate HTTP status code (400 for MessageBird client errors, 503 for timeouts, 500 for server errors), and send a structured error response back to our client.4. Handling Media Attachments
MessageBird does not accept direct file uploads via the
/mms
endpoint. You must provide publicly accessible URLs.mediaUrls
can be included in a single MMS request.Content-Type
values. Common types likeimage/jpeg
,image/png
,image/gif
,video/mp4
,audio/mpeg
are generally supported.Example
mediaUrls
Array in Request Body:5. Error Handling, Logging, and Retries
/send-mms
route includes robust error handling for API calls to MessageBird. It catches different error types (API errors, network errors) and returns informative JSON responses with appropriate HTTP status codes (400, 401, 500, 503). Fastify's default error handler catches other unexpected errors.pino
) is configured inserver.js
.LOG_LEVEL
environment variable controls verbosity. Set todebug
for more detailed logs during troubleshooting.npm run dev
), logs are human-readable thanks topino-pretty
. In production (npm start
), JSON logs are standard, which is better for log aggregation tools (like Datadog, Splunk, ELK stack).axios.post
call in a simple loop or use a library likeasync-retry
. Be cautious with retries for non-idempotent POST requests – ensure MessageBird handles duplicate requests gracefully if a retry occurs after the initial request succeeded but the response was lost. Using a uniquereference
field might help MessageBird deduplicate, but verify this behavior.6. Security Considerations
/send-mms
route definition. This prevents malformed requests and basic injection attempts./send-mms
endpoint is protected by thex-api-key
header check (fastify.authenticate
hook). EnsureFASTIFY_API_KEY
is strong and kept secret.MESSAGEBIRD_API_KEY
is sent securely via HTTPS in theAuthorization
header to MessageBird..env
locally, secure configuration management in deployment). Rotate keys periodically.max
andtimeWindow
based on expected usage.npm audit fix
oryarn audit
) to patch known vulnerabilities.7. Receiving Status Updates (Webhooks)
MessageBird can notify your application about the delivery status of sent MMS messages via webhooks.
Configure Webhook URL in MessageBird:
https://your-app-domain.com/mms-status
).Create the Status Webhook Route in Fastify: MessageBird sends status updates as GET requests to your configured URL.
Explanation:
/mms-status
for GET requests.request.query
).200 OK
response. This is vital for acknowledging receipt to MessageBird.Making Webhooks Accessible:
ngrok
(ngrok http 3000
) to expose your local server (running on port 3000) to the internet with a public URL (e.g.,https://<unique-id>.ngrok.io
). Use this ngrok URL in the MessageBird dashboard for testing.8. Testing and Verification
Thorough testing ensures your integration works correctly.
Unit Tests (Example using
tap
- Fastify's default):Add test script to
package.json
:Create a test file
test/routes/mms.test.js
:nock
: Mocks HTTP requests to the MessageBird API, preventing actual calls during tests and allowing you to simulate success/error responses.app.inject
: Fastify's utility to simulate HTTP requests to your application without needing a running server.Integration Testing:
npm run dev
).curl
or a tool like Postman/Insomnia to send requests tohttp://localhost:3000/send-mms
(or your configured port)..env
: Ensure your.env
file is populated with test credentials if possible, or be prepared to use live (but potentially costly) credentials carefully.Webhook Testing (using
ngrok
):npm run dev
ngrok http 3000
(replace 3000 if using a different port). Note the publichttps://*.ngrok.io
URL./mms-status
route when MessageBird sends status updates.ngrok
web interface (http://localhost:4040
by default) to inspect incoming webhook requests.9. Deployment
Deploying the application makes it accessible publicly.
Choose a Hosting Provider:
Prepare for Production:
.env
). Use the provider's secrets management.NODE_ENV=production
: Ensure theNODE_ENV
environment variable is set toproduction
. This disables development features (likepino-pretty
) and enables optimizations in Fastify and other libraries.package.json
start
script (node server.js
) is correct.pm2
or similar to manage the Node.js process (restarts on crash, clustering).Deployment Methods (Examples):
heroku login
heroku create
heroku config:set MESSAGEBIRD_API_KEY=... FASTIFY_API_KEY=...
etc.Procfile
exists (usually inferred for Node.js):web: npm start
git push heroku main
Dockerfile
:docker build -t fastify-mms-app .
docker run -p 3000:3000 -e MESSAGEBIRD_API_KEY=... -e FASTIFY_API_KEY=... fastify-mms-app
(Pass secrets via-e
or volume mounts).Conclusion
You have successfully built a Node.js application using Fastify to send MMS messages via the MessageBird API. This service includes essential features like configuration management, authentication, robust error handling, logging, and webhook support for status updates. Remember to prioritize security, thoroughly test your implementation, and choose a deployment strategy that fits your needs. This foundation allows you to integrate rich media messaging into your applications effectively for users in the US and Canada.