Frequently Asked Questions
Use the MessageBird API and Node.js SDK with Express to create an API endpoint that accepts recipient details, message body, and media URL. This endpoint interacts with the MessageBird API to dispatch MMS messages. The detailed setup and code are provided in the guide.
The MessageBird Node.js SDK simplifies interaction with the MessageBird REST API for sending messages, making it easier to integrate MMS functionality into Node.js applications. It handles the complexities of API calls and responses.
Dotenv loads environment variables from a .env file, which keeps sensitive credentials like your MessageBird API key out of your codebase. This improves security and makes it easier to manage different configurations.
Ngrok or localtunnel are useful when you need to test webhooks locally, particularly if you extend your application to receive messages. While not strictly necessary for sending MMS, these tools become important for two-way communication or receiving delivery reports.
Create a Node.js project, install Express, the MessageBird SDK, and dotenv. Configure environment variables for your API key and originator number, initialize the SDK, and build an Express route to handle MMS sending.
The /send-mms endpoint is a POST route in your Express app that receives requests to send MMS. It handles incoming recipient, message body, and media URL data, validates it, then uses the MessageBird API to send the MMS message accordingly.
Recipient phone numbers must be in E.164 format. This international standard ensures consistent formatting and includes the country code with a leading plus sign. Example: +12025550144.
The mediaUrl parameter in MessageBird must be publicly accessible without authentication. This is necessary for MessageBird's servers to directly fetch the media file and include it in the MMS message sent to recipients.
The MessageBird Node.js SDK provides error objects in callbacks. Inspect the err.errors array for details. Handle specific error codes (e.g., invalid recipient, insufficient balance) appropriately in your app.
Log in to your MessageBird Dashboard, navigate to the Developers section, and click the API access tab. Generate a Live key (not a test key) for sending real messages and keep it secure.
An originator is the "from" address for your MMS messages. It can be a purchased phone number or an approved alphanumeric sender ID. Purchase or configure one in your MessageBird Dashboard under Numbers, ensuring it is MMS-enabled.
Use the express-rate-limit middleware to protect your /send-mms endpoint from excessive requests. Configure parameters like windowMs and max to define the rate limit window and maximum requests allowed per window.
No, mediaUrl must be publicly accessible by the MessageBird servers. Localhost URLs are only accessible within your local network and therefore won't work for sending MMS with MessageBird.
Common problems include incorrect access keys or originator numbers, invalid recipient formats, inaccessible media URLs, and carrier-specific limitations. Carefully check these configurations and refer to the troubleshooting section for solutions.
Send MMS with Node.js, Express & MessageBird: Complete Tutorial (2025)
Build a production-ready Node.js MMS API using Express and MessageBird to send multimedia messages (images, GIFs, videos) programmatically. This tutorial covers MessageBird MMS integration with Node.js 22, Express.js, and the MessageBird Node.js SDK. You'll create a robust API endpoint that handles multimedia message delivery with proper file size validation, carrier-specific limits, error handling, and security best practices for production environments.
By the end, you'll have a functional MMS API endpoint (
POST /send-mms) that accepts recipient phone numbers, message text, and media URLs (images, GIFs, videos, PDFs) to dispatch multimedia messages through MessageBird's infrastructure. This forms a foundational building block for Node.js applications requiring rich media notifications, marketing campaigns, customer engagement, or multimedia communication features. This assumes basic understanding of Node.js, npm (or yarn), and REST APIs.Project Overview and Goals
POST /send-mms). The endpoint receives a recipient phone number, optional message body, and media URL, then uses the MessageBird Node.js SDK to send an MMS message to the recipient..envfile intoprocess.env, keeping sensitive credentials out of the codebase.System Architecture:
Prerequisites:
node --versionto check your installed version.1. Setting up the Project
Initialize your Node.js project and install dependencies.
Create Project Directory: Open your terminal or command prompt and create a new directory for your project, then navigate into it.
Initialize Node.js Project: Create a
package.jsonfile to manage dependencies and scripts.Install Dependencies: Install Express, the MessageBird SDK, and dotenv.
express: Web framework.messagebird: Official SDK for interacting with the MessageBird API.dotenv: Manages environment variables securely.Create Project Structure: Create the main application file and environment variable files.
index.js: Main application code..env: Stores sensitive credentials (API Key, Originator Number). Never commit this file to version control..env.example: Template showing required environment variables (safe to commit)..gitignore: Specifies files/directories Git should ignore.Configure
.gitignore: Addnode_modulesand.envto prevent committing them.Configure
.env.example: Add placeholders for required environment variables.MESSAGEBIRD_ACCESS_KEY: Your Live API key from the MessageBird dashboard.MESSAGEBIRD_ORIGINATOR: Phone number (in E.164 format, e.g., +12025550144) or approved Alphanumeric Sender ID you purchased/configured in MessageBird that's enabled for MMS.Configure
.env: Create a.envfile by copying.env.exampleand filling in your actual credentials.Edit
.envwith your real MessageBird Live API Key and Originator Number.Security: Keep your
.envfile secure and never share it publicly.2. Implementing Core MMS Sending Functionality
Integrate the MessageBird SDK to handle MMS sending logic.
Obtaining MessageBird API Key:
Obtaining MessageBird Originator:
+12025550144).Initialize SDK and Load Environment Variables: Open
index.jsand require dependencies, then initialize the MessageBird client using the API key from your environment variables.dotenvfirst to make environment variables available.initClientfrom themessagebirdpackage, passing the API key. A try-catch block handles potential initialization errors.express.json()middleware to parse incoming JSON requests.server.SIGTERMandSIGINT.3. Building the API Layer
Create the
/send-mmsendpoint.Define the POST Route: Add the following route handler within the
// --- Routes ---section inindex.js.POSTrequests on/send-mms.recipient,messageBody, andmediaUrlfrom the JSON request body (req.body).paramsobject required bymessagebird.messages.create.originatorcomes from environment variables.recipientsmust be an array, even for one number.bodyis included (optional but good practice).typeis set to'binary'. This usually works for images/GIFs. If you encounter issues with specific carriers or media types, consult MessageBird documentation;'premium'might be required.mediaUrlsis an array containing the public URL of the media file.reportUrl(for delivery reports) orreferenceUrlcan be added.messagebird.messages.create(params, callback)sends the request.errexists, it logs the error and sends an appropriate error response (500 or potentially 400/402 based on the MessageBird error code). Returns structured error details.responseexists), it logs the success and sends a 200 response with a structured subset of details from the MessageBird response.4. Integrating with Third-Party Services (MessageBird)
MessageBird-specific configuration:
.envfile (MESSAGEBIRD_ACCESS_KEY,MESSAGEBIRD_ORIGINATOR).dotenvloads the key intoprocess.env, preventing hardcoding. Exclude the.envfile from Git via.gitignore. Ensure server-level permissions restrict access to this file.const messagebird = initClient(process.env.MESSAGEBIRD_ACCESS_KEY);securely uses the key.MESSAGEBIRD_ACCESS_KEY: Your Live API key (e.g.,live_xxxxxxxx). Obtain from Dashboard → Developers → API access. Authenticates API requests.MESSAGEBIRD_ORIGINATOR: Your purchased/configured MessageBird number or Alphanumeric Sender ID enabled for MMS (e.g.,+12025550144). Obtain from Dashboard → Numbers. Used as the "From" address for the MMS.5. Error Handling, Logging, and Retry Mechanisms
initClientand exit gracefully if critical.messagebird.messages.createcallback receives anerrobject. Inspecterr.errorsfor specific MessageBird issues. Map MessageBird errors to appropriate HTTP status codes (e.g., auth errors -> 400/401, balance -> 402, rate limits -> 429, server errors -> 500/502).console.logandconsole.errorfor simplicity in this example. For production, use a dedicated logging library (like Winston or Pino) to:async-retry.6. Database Schema and Data Layer (Not Applicable)
This specific guide focuses solely on the transient action of sending an MMS and does not require a database. If you were building a system to track sent messages, manage templates, handle inbound replies, or correlate delivery reports, you would integrate a database (e.g., PostgreSQL, MongoDB) with an ORM/ODM (like Prisma, Sequelize, Mongoose) here. This would involve defining schemas, migrations, and data access functions.
7. Security Features
joi,zod,express-validator).URLconstructor and checking protocols (http,https).mediaUrlcould be user-controlled in a broader context (e.g., allowlist domains, disallow private IPs). MessageBird's fetch might mitigate some risks, but validating input is best practice..envand.gitignore. Ensure the server environment where this runs is secure. Consider secrets management solutions (like HashiCorp Vault, AWS Secrets Manager, Doppler, platform-native secrets) for production./send-mmsendpoint from abuse. Use libraries likeexpress-rate-limit.npm auditoryarn audit) and update them. Use tools like Snyk or Dependabot.helmetmiddleware for Express to set various HTTP headers for security.8. Handling Special Cases (MMS Specific)
mediaUrlmust be publicly accessible without authentication for MessageBird servers to fetch it. Private URLs, URLs requiring logins, or localhost URLs will fail.bodyreasonably concise.9. Performance Optimizations (Less Critical for Simple Sending)
For this simple sending endpoint, performance is less critical than reliability and correctness. However, if handling high volume:
messagebird.messages.createcall is non-blocking, allowing the server to handle other requests while waiting for MessageBird's response. Ensure no blocking operations exist in the request path.pm2for process management and clustering on multi-core machines.10. Monitoring, Observability, and Analytics
For production readiness:
/healthendpoint that returns a 200 OK status. Monitoring services (like Kubernetes probes, uptime checkers) can poll this to ensure the application is running and responsive./send-mms).reportUrlin yourmessages.createpayload (or globally in MessageBird settings). This URL points to an endpoint you create in your Express app to receive webhooks about the final delivery status (e.g.,delivered,failed,expired). Process these DLRs asynchronously, potentially updating a database record associated with the original message ID.11. Troubleshooting and Caveats
Request not allowed (incorrect access_key)(Code: 2)MESSAGEBIRD_ACCESS_KEYin.env. Using a Test key instead of a Live key (or vice-versa). Key lacks permissions..envmatches the Live key in the MessageBird Dashboard (Developers -> API access). Ensure.envis being loaded correctly (check for typos, restart server). Confirm the key is active and has message sending permissions.originator is invalidorThe originator is not allowed to send this type of message(Code: 9 or similar)MESSAGEBIRD_ORIGINATORnumber/ID in.envis incorrect, not owned by your account, misspelled, or not capable of sending MMS to the target country/carrier (e.g., using Alphanumeric where a number is required, number lacks MMS capability)..env. Check the number's capabilities in the MessageBird Dashboard (Numbers -> Manage). Ensure it's MMS-enabled for the destination. Use the full E.164 number format (+1...) if using a phone number.recipient is invalid(Code: 10)+and country code (e.g.,+12025550189). Add stricter validation on your server. Check MessageBird logs for more details if the format seems correct.mediaUrlsor fetching media (may vary, e.g.,File not accessible,Content type not supported, Code: 20)mediaUrlis not publicly accessible (behind login, firewall, private IP), incorrect URL, points to an unsupported file type, or the file exceeds size limits. Network issues between MessageBird's servers and the media host. SSL/TLS issues on the media host.reportUrlfor definitive status updates. Consult MessageBird support with specific message IDs if the issue persists and logs/DLRs don't clarify.express-rate-limitmiddleware helps protect your own API endpoint, not MessageBird's limits directly.200 OKwith statusacceptedorscheduled) means MessageBird accepted the request, not that the message was delivered. Use Delivery Reports (reportUrl) for final delivery status confirmation.12. Deployment and CI/CD
.envfile. Production deployment environments (Heroku, AWS ECS/EKS, Google Cloud Run, Azure App Service, Docker Swarm, etc.) provide mechanisms to securely inject environment variables. Use these platform-specific methods (e.g., ConfigMaps/Secrets in K8s, Task Definition environment variables in ECS, App Settings in Azure).pm2to run your Node.js application reliably in production.pm2handles:pm2usage:npm install pm2 -gpm2 start index.js -i max --name messagebird-mms-api --watch(use--watchcautiously in prod, prefer CI/CD restarts)pm2 list,pm2 logs messagebird-mms-api,pm2 stop/restart/delete messagebird-mms-api,pm2 reload messagebird-mms-api(graceful reload)ecosystem.config.jsfile forpm2configuration.pm2cluster instances.npm cioryarn install --frozen-lockfile).eslint .).npm audit --production).Dockerfile.Frequently Asked Questions (FAQ)
Q: How do I send MMS with Node.js and MessageBird?
A: Send MMS with Node.js by installing the MessageBird SDK and Express framework, creating a POST endpoint that accepts recipient numbers and media URLs, then calling
messagebird.messages.create()with themediaUrlsparameter. Configure your MessageBird API key via environment variables and ensure you have an MMS-capable originator number.Q: What file size limits apply to MMS messages?
A: MMS file size limits vary by carrier. For optimal deliverability, keep files under 500 KB. AT&T accepts up to 1 MB, Verizon accepts images up to 1.2 MB and videos up to 3.5 MB, and T-Mobile accepts up to 3 MB. All carriers reliably handle files up to 300 KB. For time-sensitive campaigns, limit files to 150 KB.
Q: What media formats are supported for MMS?
A: MMS supports common formats including JPEG, PNG, GIF for images, MP4 for videos, and PDF for documents. The MessageBird API requires publicly accessible URLs for media files – the service fetches media from your URL during message delivery. Unsupported formats or oversized files will fail with generic errors.
Q: Do I need a special phone number to send MMS with MessageBird?
A: Yes, you need a MessageBird phone number with MMS capabilities. Purchase a Virtual Mobile Number (VMN) or Toll-Free Number from the MessageBird Dashboard and verify it supports MMS for your target countries. Alphanumeric Sender IDs have limited MMS support and may not work in regions like North America.
Q: How do I handle MessageBird API errors in Node.js?
A: Handle MessageBird errors by wrapping the SDK callback in a Promise, using try/catch blocks, and checking the
error.errorsarray structure. MessageBird returns error codes and descriptions – map authentication errors to 400/401 status codes, insufficient balance to 402, and server errors to 500. Log full error objects for debugging.Q: Why are my MMS messages not being delivered?
A: MMS delivery failures typically occur due to: (1) media files not publicly accessible, (2) file sizes exceeding carrier limits, (3) unsupported media formats, (4) originator number lacking MMS capabilities, (5) recipient carrier blocking MMS, or (6) incorrect recipient phone number format. Check MessageBird Dashboard logs for detailed delivery status and carrier-specific errors.
Q: Can I send MMS to multiple recipients at once?
A: Yes, include multiple phone numbers in the
recipientsarray parameter when callingmessagebird.messages.create(). Example:recipients: ['+12005550199', '+447123456789']. MessageBird charges per recipient, and each receives the same message and media. For personalized messages to multiple recipients, send separate API requests.Q: What's the difference between MMS and SMS in Node.js?
A: MMS (Multimedia Messaging Service) supports images, videos, GIFs, and PDFs alongside text, while SMS only supports plain text. MMS requires the
mediaUrlsparameter and an MMS-capable originator number. MMS messages are significantly more expensive than SMS and have carrier-specific file size limits. Use MMS for rich media campaigns and SMS for simple text notifications.Q: How do I test MMS sending without incurring costs?
A: Test MMS sending using MessageBird's Test API key for development (messages simulate delivery without actually sending). For real testing, send to your own phone number with small file sizes to minimize costs. MessageBird doesn't charge for failed deliveries. Check the Dashboard SMS Log to verify message status without waiting for physical delivery.
Q: What Node.js version is required for MessageBird MMS?
A: MessageBird Node.js SDK works with Node.js 14+, but for modern features and security, use Node.js 22 LTS (Active LTS until October 2025, Maintenance until April 2027). If using Vite 7 for frontend integration, you need Node.js 20.19+ or 22.12+ minimum since Node.js 18 reached end-of-life in April 2025.
Q: How do I implement retry logic for failed MMS deliveries?
A: Implement retry logic using the
async-retrypackage with exponential backoff. Only retry transient errors (5xx, network timeouts) – don't retry permanent errors (4xx like authentication failures, invalid recipients). Set retry limits (3–5 attempts) with increasing delays (1s, 2s, 4s). Check the error code to distinguish permanent from transient failures.Q: Can I track MMS delivery status in real-time?
A: Yes, implement delivery reports (DLRs) by configuring a
reportUrlparameter in yourmessages.createcall. This webhook URL receives status updates (delivered, failed, expired) from MessageBird. Create an Express endpoint to receive these webhooks, validate them, and update your database records with final delivery status for each message.13. Verification and Testing
Manual Verification:
Verify your
.envfile contains the correct Live API Key and an MMS-capable Originator number.Upload a sample image (JPEG, PNG, GIF, or small MP4) to a publicly accessible URL (use Imgur for testing, or your own public server/CDN/S3 bucket with public read access). Keep the file size small (< 1 MB) for initial tests.
Start the server locally:
node index.jsUse
curl, Postman, or Insomnia to send a POST request to your running server (http://localhost:3000/send-mmsby default):Replace
+1xxxxxxxxxxwith your actual mobile number (E.164 format) capable of receiving MMS, andYOUR_PUBLICLY_ACCESSIBLE_MEDIA_URLwith the URL from step 2.Check your server logs for output (initialization, request received, payload, API response/error).
Check the response from
curl/Postman (should be 200 OK with message details on success, or an error JSON).Check your mobile phone for the MMS message (may take a few seconds to minutes).
Check the MessageBird Dashboard Logs for the message status.
Automated Testing (Conceptual):
messagebirdSDK to avoid making real API calls during unit tests. Test input validation logic, payload construction, etc.supertestto make HTTP requests to your running Express app (in a test environment). You might still mock the finalmessagebird.messages.createcall to avoid sending actual MMS and incurring costs during tests, but verify that your endpoint calls the SDK correctly with the expected parameters based on the request input.Testing Edge Cases:
recipient,mediaUrl).mediaUrl(malformed, non-existent, private).messageBody.