Frequently Asked Questions
Use the MessageBird API with Node.js and Express. Create an endpoint that takes the recipient's number, message, media URL, and uses the MessageBird SDK to send the MMS.
MessageBird is a CPaaS provider whose API enables sending SMS and MMS messages from your Node.js application. It handles the complexities of carrier integration and message delivery.
Dotenv securely manages environment variables, like API keys, keeping sensitive information separate from your code and facilitating deployment across different environments.
While not essential for simple MMS sending, a database is beneficial for tracking message status, linking messages to users, managing media, and auditing—crucial for real-world applications.
Currently, MessageBird's MMS service is limited to the US and Canada. The originator number must also be a US or Canadian MMS-enabled number obtained through MessageBird.
Each media attachment (image, video, etc.) sent via MessageBird must be 1MB (1024KB) or less. Larger files will result in an error, so optimize media beforehand.
Implement error handling at multiple levels. Use middleware like express-validator
, catch API errors within your service function, check MessageBird's error.errors
array for details, and handle route layer exceptions for robust error management.
Protect API keys with dotenv and environment variables, implement rate limiting using express-rate-limit, use HTTPS and a reverse proxy, validate all input rigorously, and implement authentication/authorization when necessary.
MessageBird supports a wide range of image, audio, video, text, and application file types. The extensive list is available in their MMS documentation for reference. MessageBird handles the type detection after fetching from the media URL.
You can include up to 10 media URLs in the mediaUrls array for each MMS message sent through the MessageBird API.
The originator is the sender ID displayed on the recipient's phone. For MMS with MessageBird, this must be an E.164 formatted, MMS-enabled virtual mobile number from your MessageBird account.
Use the express-rate-limit
middleware in your Express application. Configure parameters such as windowMs (time window), and max (maximum requests) to control the rate of incoming requests.
A dedicated service function promotes code modularity, isolates MessageBird interaction logic, and simplifies testing and reusability within your application.
Implement retry mechanisms with exponential backoff and jitter. Use a library like async-retry to handle transient errors, but ensure idempotency and avoid retrying on client-side errors.
Send MMS with Node.js, Express, and MessageBird: Complete Tutorial
This guide provides a step-by-step walkthrough for building a Node.js application using the Express framework to send Multimedia Messaging Service (MMS) messages via the MessageBird API. You'll learn everything from project setup to deployment considerations, enabling you to integrate MMS capabilities into your applications effectively.
By the end of this tutorial, you'll have a functional Express API endpoint capable of accepting requests to send MMS messages – including text and media attachments – to recipients in the US and Canada, leveraging MessageBird's reliable infrastructure.
Project Overview and Goals
What You're Building:
Create a simple Node.js Express server with a single API endpoint (
POST /send-mms
). This endpoint receives a recipient's phone number, a message subject, a message body, and a URL pointing to a media file. It then uses the MessageBird API to send an MMS message containing this information to the specified recipient.Problem Solved:
This project addresses the need to programmatically send rich media messages (images, videos, etc.) alongside text to users' mobile devices, enhancing communication beyond plain SMS. This is crucial for use cases like sending visual confirmations, promotional content, alerts with images, or multimedia notifications.
Technologies Used:
.env
file intoprocess.env
.System Architecture:
Prerequisites:
originator
).Note on MessageBird SDK Version: This guide uses the MessageBird Node.js SDK (latest stable version 4.0.1 as of 2024). The SDK is available via npm:
npm install messagebird
.Final Outcome:
A running Express application with an endpoint that, when called, sends an MMS message via MessageBird.
1. Setting Up the Project
Initialize your Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal and create a new directory for your project, then navigate into it.
Initialize npm: Initialize the project using npm. The
-y
flag accepts the default settings.Install Dependencies: Install
express
for the web server,dotenv
for managing environment variables, and themessagebird
SDK.Package Versions: This installs the latest versions of
express
(web framework),dotenv
(environment variable management), andmessagebird
(SDK v4.0.1+).Create Project Structure: Create the basic files and folders you'll need.
server.js
: The main entry point for your Express application.services/messagebirdService.js
: A module to encapsulate the logic for interacting with the MessageBird API..env
: Stores sensitive configuration like API keys (Git will ignore this file)..gitignore
: Specifies files and directories that Git should ignore.Configure
.gitignore
: Addnode_modules
and.env
to your.gitignore
file to prevent committing dependencies and sensitive credentials.Configure
.env
: Open the.env
file and add placeholders for your MessageBird API key and your MMS-enabled originator number. You'll obtain these values from your MessageBird dashboard..env
? Storing configuration like API keys directly in code is insecure and makes it hard to manage different environments (development, production)..env
files allow you to keep sensitive data separate and load it into environment variables.2. Implementing Core Functionality (MMS Sending Service)
Create a dedicated service function to handle the logic of sending the MMS message using the MessageBird SDK. This promotes separation of concerns.
Edit
services/messagebirdService.js
: Open this file and add the following code:messages.create
: The official MessageBird Node.js SDK uses themessages.create
function for sending various message types, including SMS and MMS. The presence of parameters likemediaUrls
andsubject
signals to the API that it's an MMS request.params
object required by the SDK, ensuringrecipients
andmediaUrls
are arrays.try...catch
block handles potential errors during the API call, logging them and re-throwing for the calling function (your API endpoint) to manage. Check specifically forerror.errors
which MessageBird often uses for detailed validation issues.3. Building the API Layer
Set up the Express server and create the
/send-mms
endpoint.Edit
server.js
: Add the following code to set up the Express app, load environment variables, initialize the MessageBird client, and define the API route.dotenv.config()
: Loads variables from.env
at the start.express.json()
: Middleware needed to parse incoming JSON request bodies (req.body
)./health
Endpoint: A simple route to check if the server is running./send-mms
Route:POST
method as it creates a resource (an MMS message request).validateSendMmsRequest
middleware first.req.body
.originator
number from environment variables.sendMms
service function.200 OK
and MessageBird's response details on success.400 Bad Request
if validation fails (handled by middleware).500 Internal Server Error
if thesendMms
function throws an error.app.listen
: Starts the server on the specified port.4. Integrating with MessageBird (Configuration Details)
Proper configuration is key to connecting your application with MessageBird.
Obtain API Key:
.env
file as the value forMESSAGEBIRD_API_KEY
. Remember to replace the placeholderYOUR_MESSAGEBIRD_LIVE_API_KEY
.Obtain MMS-Enabled Originator Number:
+1xxxxxxxxxx
)..env
file as the value forMESSAGEBIRD_ORIGINATOR
. Remember to replace the placeholder+120XXXXXXXX
.Environment Variables Explained:
MESSAGEBIRD_API_KEY
: (Required) Your secret key to authenticate requests with the MessageBird API. Found under Developers -> API access. Must be replaced by user.MESSAGEBIRD_ORIGINATOR
: (Required) The MMS-enabled phone number (in E.164 format) that will appear as the sender of the MMS. Found under Numbers. Must be replaced by user.PORT
: (Optional) The port your Express server will listen on. Defaults to 3000 if not set.5. Error Handling, Logging, and Retry Mechanisms
Robust error handling and logging are crucial for production applications.
Error Handling Strategy:
validateSendMmsRequest
) before hitting the service layer. Return400 Bad Request
with clear error messages.sendMms
): Catch errors specifically from the MessageBird API call within the service function. Log detailed errors provided by the SDK (error.errors
). Re-throw a standardized or the original error./send-mms
): Use atry...catch
block around the call to the service function. Catch errors thrown by the service. Return500 Internal Server Error
for unexpected issues or specific MessageBird API failures. Log the error server-side.process.exit(1)
).Logging:
console.log
andconsole.error
for demonstration.Winston
orPino
. These offer structured logging (JSON format is common), different log levels (debug, info, warn, error), and configurable outputs (console, file, external logging services).Retry Mechanisms:
Network issues or temporary MessageBird glitches can cause requests to fail intermittently. Implementing retries can improve reliability.
Strategy: Use exponential backoff. Wait a short period before the first retry, then double the wait time for each subsequent retry, up to a maximum number of attempts. Add slight jitter (randomness) to wait times to avoid coordinated retries from multiple instances.
Implementation: While you could implement this manually, libraries like
async-retry
simplify this process significantly.Retry Best Practice (2024): Only retry on potentially transient errors (5xx server errors, network timeouts). Do NOT retry on client errors (4xx) such as invalid API key (401), invalid parameters (400), or rate limits (429). MessageBird's API uses standard HTTP status codes.
Example Concept (using
async-retry
- requiresnpm install async-retry
):Caution: Only retry idempotent operations (sending the same MMS multiple times should ideally have the same effect as sending it once, though billing might occur per attempt). Be cautious retrying operations that could cause duplicate actions if the initial request did succeed but the response was lost. MessageBird's API is generally safe for retrying sends if you use a unique
reference
.6. Database Schema and Data Layer (Optional for this Guide)
For this specific guide focused only on sending a single MMS via API, a database is not strictly required. However, in a real-world application, you would likely need a database to:
id
returned by MessageBird and use webhooks (see MessageBird docs) to receive status updates (sent, delivered, failed) and update your database accordingly.If adding a database:
MmsMessages
(message_id
(PK),messagebird_id
(unique),recipient
,originator
,subject
,body
,media_url
,status
,submitted_at
,last_updated_at
,reference
,user_id
(FK)).Sequelize CLI
orPrisma Migrate
to manage database schema changes over time.7. Security Features
Securing your API endpoint and credentials is vital.
Input Validation and Sanitization:
validateSendMmsRequest
). Crucially, use a dedicated library likeexpress-validator
for production. It provides robust validators (e.g.,isMobilePhone(locale, { strictMode: true })
,isURL()
,isLength()
) and sanitizers.express-validator
also offer sanitizers (trim()
,escape()
).Protect API Keys:
.env
and.gitignore
.Rate Limiting:
Prevent abuse and brute-force attacks by limiting the number of requests a client can make to your API endpoint within a certain time frame.
Implementation: Use middleware like
express-rate-limit
.Authentication/Authorization (Beyond this Guide):
/send-mms
endpoint is open. In a real application, you would protect it.HTTPS:
8. Handling Special Cases (MessageBird MMS Specifics)
Be aware of MessageBird's constraints and requirements for MMS. Source: MessageBird MMS API Documentation (verified 2024).
originator
number must be a US or Canadian MMS-enabled VMN (Virtual Mobile Number). Sending to numbers outside these countries will fail.body
(text) ORmediaUrls
(array of media URLs), or both. At least one must be present for a valid MMS request. Theoriginator
andrecipients
are always required.mediaUrls
provided must point to publicly accessible resources. MessageBird's servers need to fetch the content from these URLs. Private URLs or those behind firewalls will not work.mediaUrls
array per message.audio/basic
,audio/L24
,audio/mp4
,audio/mpeg
,audio/ogg
,audio/vorbis
,audio/vnd.rn-realaudio
,audio/vnd.wave
,audio/3gpp
,audio/3gpp2
,audio/ac3
,audio/webm
,audio/amr-nb
,audio/amr
video/mpeg
,video/mp4
,video/quicktime
,video/webm
,video/3gpp
,video/3gpp2
,video/3gpp-tt
,video/H261
,video/H263
,video/H263-1998
,video/H263-2000
,video/H264
image/jpeg
,image/gif
,image/png
,image/bmp
text/vcard
,text/csv
,text/rtf
,text/richtext
,text/calendar
application/pdf
subject
: Maximum 256 characters (UTF-8).body
: Maximum 2,000 characters (UTF-8).+12025551234
). Alphanumeric sender IDs are not supported for MMS.+16505551234
).9. Performance Optimizations
For this specific task (a single API call), major performance tuning is less critical than reliability, but consider these points for scaling:
async/await
ensures that the server isn't blocked while waiting for the MessageBird API response, allowing it to handle other requests concurrently.console.log
) can impact performance. Use asynchronous loggers (provided by libraries like Pino/Winston).k6
,Artillery
, orApacheBench (ab)
to simulate traffic to your/send-mms
endpoint and identify bottlenecks under load. Monitor CPU, memory, and response times.cluster
module or a process manager likePM2
in cluster mode to run multiple instances of your application.10. Monitoring, Observability, and Analytics
Understanding how your service performs and identifying issues requires monitoring.
/health
endpoint provides a basic mechanism for load balancers or monitoring services (like UptimeRobot, Pingdom) to check if the application instance is running./send-mms
, high API latency, low health check success rate) or logs (e.g., specific error messages) using your monitoring or error tracking tools.11. Troubleshooting and Caveats
Common issues you might encounter:
Error:
Authentication failed
(MessageBird API)MESSAGEBIRD_API_KEY
..env
file matches the Live access key in your MessageBird dashboard (Developers -> API access). Ensure there are no typos or extra spaces and that you replaced the placeholder.Error:
recipient is invalid
orInvalid parameters
(pointing to recipient)+
or country code) or is not a valid mobile number.+
and country code (e.g.,+16505551234
). Use validation (express-validator
'sisMobilePhone
) to check the format before sending.Error:
originator is invalid
orOriginator not allowed for this country
MESSAGEBIRD_ORIGINATOR
number in your.env
file is incorrect, not MMS-enabled, not a valid US/Canadian number for MMS sending, or the placeholder was not replaced..env
.Error:
media_url is invalid or inaccessible
orMedia download failed
mediaUrl
provided is not public, incorrect, timed out during fetch (longer than ~5s), or points to a resource MessageBird couldn't access.Error:
File size exceeds limit
or similar related to media size/typemediaUrl
is larger than 1MB or is not a supported media type.MMS Not Received:
id
returned in the API response). Look forsent
,buffered
,delivered
, ordelivery_failed
statuses.originator
number is correctly configured for MMS and replaced in.env
.Caveats:
12. Deployment and CI/CD
Deploy your Node.js application to production.
Environment Configuration:
.env
file. Production environments require setting environment variables (MESSAGEBIRD_API_KEY
,MESSAGEBIRD_ORIGINATOR
,NODE_ENV=production
,PORT
) through the hosting provider's interface or system environment variables. Ensure the actual keys/numbers are used, not placeholders.NODE_ENV=production
to enable Express optimizations and potentially disable verbose logging or development features.Hosting Options:
Process Manager:
PM2
orNodemon
(for development) to keep your application running, manage restarts on crashes, handle clustering, and facilitate zero-downtime reloads.PM2
):Build Step (If Applicable):
npm run build
) before starting the application.CI/CD Pipeline:
npm ci
), runs linters/formatters, runs tests (npm test
).Reverse Proxy (Recommended for IaaS/Containers):
Frequently Asked Questions
What is MMS and how is it different from SMS?
MMS (Multimedia Messaging Service) allows you to send messages with media attachments (images, videos, audio, PDFs) alongside text, while SMS (Short Message Service) is limited to plain text only. MMS provides richer communication capabilities for marketing campaigns, notifications with images, and multimedia content delivery.
Which countries does MessageBird support for MMS?
MessageBird currently supports MMS sending only in the United States and Canada. Your originator number must be a US or Canadian MMS-enabled Virtual Mobile Number (VMN) purchased from MessageBird.
What file types can I send via MessageBird MMS?
MessageBird supports 34+ MIME types including:
Each attachment must be 1 MB or less, and you can include up to 10 attachments per message.
How do I get a MessageBird API key?
Log in to your MessageBird Dashboard, navigate to Developers → API access, and click Add access key. Choose a Live key for production use. Store this key securely in your
.env
file and never commit it to version control.What's the maximum message size for MMS via MessageBird?
The character limits are:
How do I handle MMS delivery failures?
Implement error handling in your code to catch MessageBird API errors. Check the
error.errors
array for detailed error descriptions. Common failures include invalid phone numbers (use E.164 format), inaccessible media URLs, files exceeding 1 MB, or unsupported media types. Use the message ID returned by the API to track delivery status via MessageBird's dashboard or webhooks.Can I schedule MMS messages for later delivery?
Yes, use the
scheduledDatetime
parameter in RFC3339 format (e.g.,2025-12-31T10:30:00+00:00
) when calling the MessageBird API. This allows you to queue messages for future delivery.What Node.js version should I use with MessageBird SDK?
The MessageBird Node.js SDK (v4.0.1) is compatible with Node.js 12.x and higher. For production applications, use the latest LTS (Long Term Support) version of Node.js for optimal security and performance.
How do I test MMS sending without incurring costs?
MessageBird does not offer a free sandbox for MMS testing – all MMS messages sent incur charges. Consider:
What's the difference between
body
andmediaUrls
parameters?Per MessageBird's API specification, you must provide either
body
(text content) ormediaUrls
(array of media file URLs), or both. At minimum, one must be present. An MMS with only media and no text is valid, as is one with only text (though that's essentially an SMS).Summary
You've built a complete Node.js Express application for sending MMS messages via MessageBird's API. This implementation includes:
The application is ready for deployment and can be extended with features like database integration, webhook handling for delivery status updates, and authentication/authorization for production use.
For additional resources, consult the MessageBird API Documentation and the MessageBird Node.js SDK repository.