Tutorials

Send MMS with MessageBird Node.js API: Complete Express Tutorial

Step-by-step guide to sending MMS messages with MessageBird API using Node.js and Express. Includes multimedia messaging code examples, error handling, security best practices, and US/Canada MMS delivery.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 1, 2026 β€’ 18 min read

Developer Quick-Start: Step-by-step guide to sending MMS messages with MessageBird API using Node.js and Express. Includes multimedia messaging code examples, error handling, security best practices, and US/Canada MMS delivery. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.

Learn how to send MMS (Multimedia Messaging Service) messages using the MessageBird API with Node.js and Express. This comprehensive tutorial covers everything from initial setup to production deployment, enabling you to send images, videos, and other media files directly to mobile devices in the US and Canada.

Important: Geographic Restrictions – MessageBird MMS works only within the United States and Canada. For other countries, use an alternative service.

Technical Specifications:

  • Maximum file size: 1 MB (1,024 KB) per attachment
  • Maximum attachments: 10 per message
  • Body character limit: 2,000 characters
  • Subject character limit: 256 characters
  • Media URL response timeout: 5 seconds (URLs must respond within this timeframe)
  • Supported formats: JPEG, PNG, GIF, BMP (images); MP3, OGG (audio); MP4, WebM, QuickTime (video); PDF, vCard, CSV, RTF (documents)

You'll build a REST API endpoint that accepts recipient details, a text message body, and a URL for the media file, then uses the MessageBird SDK to send the MMS message. This guide covers setup, implementation, security, error handling, deployment considerations, and verification.

Technologies Used:

  • Node.js: A JavaScript runtime environment for server-side development.
  • Express: A minimal and flexible Node.js web application framework.
  • MessageBird Node.js SDK: Simplifies interaction with the MessageBird REST API. Current version: 4.0.1 (last updated approximately 3 years ago as of 2024-2025). While the SDK hasn't received recent updates, it remains functional with MessageBird's REST API.
  • dotenv: A module to load environment variables from a .env file.

Note on SDK Status: The MessageBird Node.js SDK (npm package messagebird) is at version 4.0.1 and has not been updated since approximately 2021-2022. While this may indicate limited active development, the SDK continues to work with MessageBird's API. For production applications, consider monitoring the GitHub repository (messagebird/messagebird-nodejs) for any updates or security patches.

System Architecture:

A typical flow involves a client application sending a request to your Node.js/Express API. Your API then calls the MessageBird API with the MMS details (including the media URL). MessageBird fetches the media and sends the MMS to the recipient's device. Optionally, MessageBird can send status updates back to your API via webhooks. Your API responds to the initial client request indicating success or failure.

Prerequisites:

  • Node.js and npm (or yarn) installed.
  • A MessageBird account with a valid API key and an available virtual mobile number (VMN) or Alphanumeric Sender ID configured for sending messages. VMN (Virtual Mobile Number) is generally recommended for MMS.
  • A publicly accessible URL for the media file you want to send (e.g., stored in cloud storage like AWS S3, Google Cloud Storage, or a public web server). MessageBird needs to retrieve the file from this URL.
  • Basic understanding of Node.js, Express, and REST APIs.

By the end of this guide, you will have a functional Express application capable of accepting API requests to send MMS messages reliably using MessageBird.

1. Setting Up Your Node.js Project for MessageBird MMS Integration

Let's start by creating our project directory, initializing Node.js, and installing the necessary dependencies for MessageBird MMS integration.

  1. Create Project Directory: Open your terminal and create a new directory for your project, then navigate into it.
   mkdir node-messagebird-mms
   cd node-messagebird-mms
  1. Initialize Node.js Project: This command creates a package.json file to manage project dependencies and metadata.
   npm init -y

The -y flag accepts the default settings.

  1. Install Dependencies: We need express for the web server, messagebird for the SDK, and dotenv to manage environment variables securely.
   npm install express messagebird dotenv
  1. Create Project Structure: Create the main application file.
   touch index.js

Create a file to store environment variables.

   touch .env

Create a .gitignore file to prevent sensitive information and unnecessary files from being committed to version control.

   touch .gitignore
  1. Configure .gitignore: Add the following lines to your .gitignore file to exclude the node_modules directory and the .env file (which will contain your API key).
   # .gitignore
   node_modules
   .env

Why? Keeping node_modules out of Git prevents bloating the repository. Excluding .env prevents accidentally committing sensitive API keys.

  1. Configure Environment Variables (.env): Open the .env file and add your MessageBird API key and the originator (sender) phone number or Alphanumeric ID.

.env

   # .env
   MESSAGEBIRD_API_KEY=YOUR_LIVE_API_KEY
   MESSAGEBIRD_ORIGINATOR=YOUR_SENDER_NUMBER_OR_ID
  • MESSAGEBIRD\_API\_KEY: Your live API key obtained from the MessageBird Dashboard (Developers -> API access). Ensure it's the live key, not the test key, for sending actual messages.
  • MESSAGEBIRD\_ORIGINATOR: The phone number (in E.164 format, e.g., +12025550142) or approved Alphanumeric Sender ID you want the message to appear from. Check MessageBird documentation for country restrictions, especially regarding Alphanumeric Sender IDs. Using a purchased MessageBird virtual number is recommended for reliable two-way communication and MMS support.
  1. Basic Express Server Setup (index.js): Open index.js and set up a minimal Express application.
   require('dotenv').config();
   const express = require('express');
   const messagebird = require('messagebird').initClient(process.env.MESSAGEBIRD_API_KEY);

   const app = express();
   const port = process.env.PORT || 3000;

   app.use(express.json());

   app.get('/health', (req, res) => {
     res.status(200).send('Server is healthy');
   });

   app.listen(port, () => {
     console.log(`Server listening on port ${port}`);
   });

   if (!process.env.MESSAGEBIRD_API_KEY) {
     console.error("FATAL ERROR: MESSAGEBIRD_API_KEY is not set in the environment variables.");
     process.exit(1);
   }

   console.log('MessageBird SDK initialized.');

Why dotenv.config() first? It needs to load variables before they are accessed by messagebird.initClient. Why express.json()? This middleware is crucial for parsing the JSON payload we'll send to our API endpoint. Why initClient? The official SDK requires using .initClient() to instantiate the client with your API key, as confirmed by documentation and common issues.

You now have a basic Node.js Express project structure ready for implementing the MMS sending functionality.

2. Implementing the MessageBird MMS Sending Function

The core logic involves using the messagebird.messages.create method from the SDK, providing not just the standard SMS parameters but also the specific MMS details.

  1. Define the sendMms Function: It's good practice to encapsulate the sending logic in a reusable function. Let's add this within index.js, before the app.listen call.
   function sendMms(recipient, body, mediaUrl) {
     return new Promise((resolve, reject) => {
       const params = {
         originator: process.env.MESSAGEBIRD_ORIGINATOR,
         recipients: [recipient],
         body: body,

         mms: {
           mediaUrls: [mediaUrl]
         }
       };


       if (!params.originator || !recipient || !body || !mediaUrl) {
          return reject(new Error('Missing required parameters for sending MMS.'));
       }
       if (!params.mms.mediaUrls[0].startsWith('http')) {
          return reject(new Error('Invalid mediaUrl format. It must be a publicly accessible URL.'));
       }


       if (body.length > 2000) {
          return reject(new Error(`Message body exceeds maximum length of 2,000 characters. Current length: ${body.length}`));
       }




       console.log(`Attempting to send MMS to ${recipient} with media: ${mediaUrl}`);

       messagebird.messages.create(params, (err, response) => {
         if (err) {

           console.error("MessageBird API Error:", JSON.stringify(err, null, 2));

           const errorMessage = err.errors ? err.errors.map(e => e.description).join(', ') : 'Unknown MessageBird API error';
           return reject(new Error(`Failed to send MMS: ${errorMessage}`));
         }

         console.log("MessageBird API Success:", JSON.stringify(response, null, 2));
         resolve(response);
       });
     });
   }

Why the mms object? This is the key difference from sending SMS. The MessageBird API requires MMS-specific parameters, like mediaUrls, to be nested within an mms object in the request payload. mediaUrls must be an array of strings, each being a publicly accessible URL. Why a Promise? The messagebird.messages.create method uses a callback pattern. Wrapping it in a Promise allows us to use async/await syntax in our API route handler for cleaner asynchronous code. Why basic validation? Checking for required parameters and a valid URL format before calling the API prevents unnecessary API calls and provides immediate feedback for invalid requests.

3. Creating a REST API Endpoint to Send MMS Messages

Now, let's create the Express API endpoint that will use our sendMms function to handle incoming MMS requests.

  1. Create the POST /send-mms Route: Add the following route handler to your index.js file, typically after the /health route and before app.listen.
   app.post('/send-mms', async (req, res) => {
     const { recipient, body, mediaUrl } = req.body;


     if (!recipient) {
       return res.status(400).json({ error: 'Recipient phone number is required.' });
     }
     if (!body) {
       return res.status(400).json({ error: 'Message body is required.' });
     }
     if (!mediaUrl) {
       return res.status(400).json({ error: 'Media URL is required.' });
     }

     if (!/^\+[1-9]\d{1,14}$/.test(recipient)) {
        return res.status(400).json({ error: 'Invalid recipient phone number format. Use E.164 format (e.g., +12025550142).' });
     }
      if (!mediaUrl.startsWith('http://') && !mediaUrl.startsWith('https://')) {
        return res.status(400).json({ error: 'Invalid mediaUrl. Must be a public HTTP or HTTPS URL.' });
     }


     try {

       const messageBirdResponse = await sendMms(recipient, body, mediaUrl);


       res.status(200).json({
         message: 'MMS sent successfully.',
         details: {
            id: messageBirdResponse.id,
            status: messageBirdResponse.recipients.items[0].status,
            recipient: messageBirdResponse.recipients.items[0].recipient
         }
       });
     } catch (error) {

       console.error('Error in /send-mms route:', error.message);



       res.status(500).json({ error: `Failed to send MMS. ${error.message}` });
     }
   });

Why async/await? It simplifies handling the Promise returned by our sendMms function, making the asynchronous code look more synchronous and readable. Why status codes? Using appropriate HTTP status codes (200 for success, 400 for bad input, 500 for server errors) is standard practice for REST APIs. Why basic validation here too? While sendMms has some checks, validating input at the API boundary is crucial for security and user feedback before attempting business logic. More robust validation (e.g., using express-validator) is recommended for production. Why return limited details? We return the MessageBird message ID and initial status, which are useful for tracking, but avoid exposing the full internal API response.

  1. Testing the Endpoint: You can test this endpoint using tools like curl or Postman. Make sure your server is running (node index.js).

Using curl: Replace placeholders with your actual recipient number and a publicly accessible media URL.

   curl -X POST http://localhost:3000/send-mms \
   -H "Content-Type: application/json" \
   -d '{
     "recipient": "+1xxxxxxxxxx",
     "body": "Check out this cool image!",
     "mediaUrl": "https://www.example.com/path/to/your/public/image.jpg"
   }'

Expected Success Response (JSON):

   {
     "message": "MMS sent successfully.",
     "details": {
       "id": "mb-message-id-string",
       "status": "sent",
       "recipient": 31612345678
     }
   }

Expected Error Response (JSON - e.g., Bad Input):

   {
     "error": "Recipient phone number is required."
   }

(Status Code: 400) Expected Error Response (JSON - e.g., API Failure):

   {
      "error": "Failed to send MMS. Failed to send MMS: The originator is incorrect."
   }

(Status Code: 500)

4. Getting Your MessageBird API Credentials

This section details obtaining and managing the necessary MessageBird credentials for MMS integration.

  1. Obtain API Key:
  • Log in to your MessageBird Dashboard.
  • Navigate to the "Developers" section in the left-hand menu.
  • Click on the "API access" tab.
  • If you don't have a key, click "Add access key".
  • Ensure you are using a Live API Key, not a test key. Copy the key.
  1. Obtain Originator Number/ID:
  • You need a way to identify the sender. This can be:
  • Virtual Mobile Number (VMN): Purchase a number from MessageBird ("Numbers" section -> "Buy a number"). Select one with SMS/MMS capabilities in your desired country. This is generally recommended for MMS.
  • Alphanumeric Sender ID: Apply for one under "Numbers" -> "Sender IDs". Approval is required, and support varies by country (often not supported for MMS or in regions like the US/Canada).
  • Copy the number (in E.164 format, e.g., +12025550142) or the approved Sender ID.
  1. Securely Store Credentials:
  • As configured in Step 1, place your Live API Key and Originator into the .env file:

.env

     # .env
     MESSAGEBIRD_API_KEY=your_copied_live_api_key_here
     MESSAGEBIRD_ORIGINATOR=+1yourpurchasednumber
  • Never commit .env files to version control. Use the .gitignore entry created earlier.
  • For production environments, use your hosting provider's secret management system (e.g., Heroku Config Vars, AWS Secrets Manager, GCP Secret Manager) instead of deploying a .env file.
  1. Understanding Environment Variables:
  • MESSAGEBIRD\_API\_KEY: (String) Your unique key to authenticate with the MessageBird API. It proves your identity. Obtained from the MessageBird Dashboard's Developer section.
  • MESSAGEBIRD\_ORIGINATOR: (String) The sender identifier (phone number in E.164 format or Alphanumeric ID) that will appear on the recipient's device. Obtained from the MessageBird Dashboard's Numbers section (either purchased VMN or approved Sender ID). Must be capable of sending messages in the target country/network.

5. Error Handling and Logging for MMS Applications

Robust applications need to handle failures gracefully and maintain comprehensive logs for troubleshooting.

  1. Error Handling Strategy:
  • API Boundary: Validate inputs at the start of the /send-mms route (as implemented) to catch malformed requests early (4xx errors).
  • Service Layer: Use try...catch blocks around API calls (messagebird.messages.create) to handle network issues or API-specific errors (5xx errors).
  • SDK Callback: The messagebird.messages.create callback provides an err object containing detailed error information from the API (e.g., invalid recipient, insufficient balance, invalid originator). We log this detailed error on the server but return a more generic message to the client.
  1. Logging:
  • Our current implementation uses console.log and console.error. For production, use a dedicated logging library like winston or pino.
  • Key Events to Log:
  • Successful MMS submission (with MessageBird ID).
  • API call failures (with the err object from MessageBird).
  • Input validation errors.
  • Server startup/shutdown.
  • Log Format: Include timestamps, log levels (INFO, ERROR, WARN), and contextual information (e.g., recipient, attempted action). JSON format is often preferred for easier parsing by log analysis tools.
   console.error(`[${new Date().toISOString()}] ERROR: Failed to send MMS for recipient ${recipient}. Reason: ${error.message}`);

   console.info(`[${new Date().toISOString()}] INFO: Successfully submitted MMS to ${recipient}. MessageBird ID: ${messageBirdResponse.id}`);
  1. Retry Mechanisms:
  • Network glitches or temporary MessageBird issues might cause transient failures. Implementing retries can improve reliability.
  • Strategy: Use exponential backoff (wait increasingly longer times between retries) to avoid overwhelming the API. Limit the number of retries.
  • Implementation: Libraries like async-retry or p-retry can simplify this. For this guide, we'll keep it simple and mention the concept.
  • Caveat: Only retry on potentially transient errors (e.g., network timeouts, 5xx errors from MessageBird). Do not retry on permanent errors like invalid API keys (401), invalid recipients (invalid\_recipient), or insufficient funds. Check the err.statusCode or err.errors[0].code from the MessageBird response.

JavaScript

  1. Testing Error Scenarios:
  • Send requests with missing recipient, body, or mediaUrl (expect 400).
  • Send with an invalid E.164 number (expect 400).
  • Temporarily set an incorrect MESSAGEBIRD\_API\_KEY in .env (expect 500 with auth error).
  • Use an invalid MESSAGEBIRD\_ORIGINATOR (expect 500 with originator error).
  • Use a non-public or malformed mediaUrl (expect 400 or 500 depending on when error is caught).
  • Simulate network issues if possible.

6. Optional: Database Integration for MMS Message Tracking

While not strictly necessary for sending, storing message status or logs locally can be useful for tracking, analytics, or building more complex workflows (like handling status updates via webhooks).

  1. Conceptual Schema (e.g., PostgreSQL):
   CREATE TABLE mms_log (
       id SERIAL PRIMARY KEY,
       messagebird_id VARCHAR(255) UNIQUE,
       recipient VARCHAR(20) NOT NULL,
       sender VARCHAR(20) NOT NULL,
       body TEXT,
       media_url VARCHAR(2048),
       status VARCHAR(50),
       error_code INT,
       error_description TEXT,
       submitted_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
       last_updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
   );

   CREATE INDEX idx_mms_log_messagebird_id ON mms_log(messagebird_id);

   CREATE INDEX idx_mms_log_recipient ON mms_log(recipient);
  1. Data Access Layer:
  • You would use an ORM like Sequelize or Prisma, or a query builder like Knex.js to interact with the database.
  • Insert on Send: After successfully calling messagebird.messages.create, insert a record into mms\_log with the messagebird\_id, recipient, initial status ('submitted' or 'sent'), etc.
  • Update via Webhooks (Advanced): Configure MessageBird status report webhooks. Create another API endpoint (e.g., /message-status) to receive these updates. When a webhook arrives, find the corresponding record in mms\_log using the messagebird\_id and update its status, error\_code, etc.

This guide focuses on sending; implementing the database and webhook handling is a separate, more involved task.

7. Security Best Practices for MessageBird MMS APIs

Protecting your API and credentials is vital for maintaining secure MMS operations.

  1. Input Validation and Sanitization:
  • We implemented basic validation. For production, use a dedicated library like express-validator:
     npm install express-validator
     const { body, validationResult } = require('express-validator');

     app.post('/send-mms',

       body('recipient').isMobilePhone('any', { strictMode: true }).withMessage('Invalid E.164 recipient format.'),
       body('body').notEmpty().trim().escape().withMessage('Body cannot be empty.'),
       body('mediaUrl').isURL({ protocols: ['http', 'https'], require_protocol: true }).withMessage('Invalid or non-public media URL.'),

       async (req, res) => {
         const errors = validationResult(req);
         if (!errors.isEmpty()) {
           return res.status(400).json({ errors: errors.array() });
         }

         const { recipient, body: validatedBody, mediaUrl } = req.body;

       }
     );
  • trim() removes whitespace, escape() prevents basic XSS by escaping HTML entities (important if displaying this data later). isMobilePhone with strictMode helps enforce E.164. isURL validates the media link.
  1. Secure API Key Handling:
  • Use environment variables (.env locally, secure config management in production).
  • Never hardcode keys in source code.
  • Restrict API key permissions in the MessageBird dashboard if possible (though MessageBird keys are often account-wide).
  1. Rate Limiting:
  • Prevent abuse and brute-force attacks by limiting the number of requests from a single IP address. Use express-rate-limit:
     npm install express-rate-limit
     const rateLimit = require('express-rate-limit');

     const apiLimiter = rateLimit({
       windowMs: 15 * 60 * 1000,
       max: 100,
       message: 'Too many requests from this IP, please try again after 15 minutes',
       standardHeaders: true,
       legacyHeaders: false,
     });

     app.use('/send-mms', apiLimiter);
  1. Webhook Security (If Implementing Status Updates):
  • MessageBird signs webhook requests using JWT (JSON Web Tokens) in the MessageBird-Signature-JWT header.
  • Verify these signatures to ensure requests genuinely come from MessageBird. The messagebird-nodejs SDK provides a helper function.
  • You'll need your Webhook Signing Key from the MessageBird Dashboard (Developers -> API Settings -> Webhook Signing Key). Store this securely like your API key (e.g., in .env locally using a variable like MESSAGEBIRD\_WEBHOOK\_SIGNING\_KEY, or using production secrets management).

JavaScript Why express.raw? Signature verification must happen on the raw, unmodified request body. express.json() parses the body, which alters it.

8. MessageBird MMS Requirements and Limitations

MMS sending has specific nuances and strict technical requirements:

  1. Geographic Restrictions: MessageBird MMS is only available for sending within the United States and Canada (as of 2024-2025). Attempting to send MMS to recipients in other countries will fail. If you need international MMS, consider alternative providers.
  2. Media URL Accessibility and Timeout: The mediaUrl must point to a resource publicly accessible on the internet without authentication. Critical: MessageBird's servers must be able to fetch the file within 5 seconds. URLs that take longer to respond will cause the MMS to fail. Private S3 buckets, password-protected URLs, or localhost URLs will not work.
  3. Media File Types and Sizes (Verified Specifications):
  • Maximum file size: 1MB (1,024KB) per attachment
  • Maximum attachments: 10 per message
  • Supported image formats: JPEG, PNG, GIF, BMP
  • Supported video formats: MP4, WebM, QuickTime (.mov)
  • Supported audio formats: MP3, OGG
  • Supported document formats: PDF, vCard (.vcf), CSV, RTF
  • Sending unsupported file types or files exceeding 1MB will result in API errors.
  1. Character Limits (Verified Specifications):
  • Message body: 2,000 characters maximum (not just "practical limits")
  • Subject line: 256 characters maximum (if using the optional subject parameter)
  • Messages exceeding these limits will be rejected by the API.
  1. Recipient Limits: Maximum of 50 recipients per API request. For larger distributions, batch your requests.
  2. Originator Restrictions: Alphanumeric Sender IDs are not supported for MMS in North America (US/Canada). You must use a purchased MessageBird Virtual Mobile Number (VMN) with MMS capabilities. Attempting to send MMS from an alphanumeric sender ID will fail.
  3. Recipient Country/Carrier Support: MMS rendering varies between mobile carriers. Some carriers may convert MMS to SMS with a link to view media. Always test with your target carriers before production deployment.
  4. Character Encoding: Ensure your text body uses UTF-8 encoding. Special characters, emojis, or non-standard character sets may render incorrectly or increase character count.

9. Performance Optimization for High-Volume MMS Sending

For high-volume sending, consider these optimization strategies to maximize throughput and reliability.

  1. Asynchronous Operations: Node.js is inherently non-blocking. Our use of async/await and callbacks ensures the server isn't blocked waiting for MessageBird's API response, allowing it to handle other requests concurrently.
  2. Connection Pooling: The MessageBird SDK likely handles underlying HTTP connection management. Ensure your Node.js process has sufficient resources (memory, CPU).
  3. Media File Optimization: Use reasonably sized and compressed media files. Smaller files transfer faster and are less likely to hit size limits.
  4. Payload Size: Keep the JSON request payload to your API minimal.
  5. Load Testing: Use tools like k6, Artillery, or ApacheBench to simulate high traffic and identify bottlenecks in your API endpoint or the downstream MessageBird service. Monitor response times and error rates under load.
  6. Horizontal Scaling: Deploy multiple instances of your Node.js application behind a load balancer to distribute traffic.

10. Monitoring and Analytics for MMS Delivery

Understanding how your service behaves in production is crucial for maintaining reliable MMS delivery.

  1. Health Checks: The /health endpoint is a basic start. Production health checks might verify database connectivity or dependency availability.
  2. Performance Metrics: Monitor key metrics:
  • Request latency (average, p95, p99) for the /send-mms endpoint.
  • Request rate (requests per second/minute).
  • Error rates (HTTP 4xx, 5xx).
  • Node.js process metrics (CPU usage, memory usage, event loop lag).
  • Use tools like Prometheus/Grafana, Datadog, or New Relic.
  1. Error Tracking: Integrate services like Sentry or Bugsnag. They automatically capture unhandled exceptions and provide detailed context (stack traces, request data) for faster debugging.
  2. Logging Aggregation: Ship logs (using Winston/Pino) to a centralized logging platform (e.g., Elasticsearch/Logstash/Kibana (ELK), Datadog Logs, Splunk) for searching, analysis, and alerting.
  3. MessageBird Dashboard: Regularly check the MessageBird Message Logs for detailed delivery statuses, error codes, and cost information. This is invaluable for troubleshooting specific message failures.
  4. Alerting: Set up alerts based on key metrics (e.g., high error rate, increased latency, low message success rate reported by webhooks/logs) using your monitoring or logging platform.

11. Troubleshooting Common MessageBird MMS Integration Issues

Common issues developers encounter when implementing MessageBird MMS:

  1. Error: require(...) is not a function or initClient is not a function
  • Cause: Incorrectly initializing the MessageBird SDK.
  • Solution: Ensure you use require('messagebird').initClient('<YOUR\_ACCESS\_KEY>'); as shown in the documentation and examples.
  1. Error: Request not allowed (incorrect access_key) (Code: 2)
  • Cause: Invalid or incorrect MESSAGEBIRD\_API\_KEY used. It might be a test key instead of live, mistyped, or lack permissions.
  • Solution: Double-check your .env file. Ensure you copied the full Live API key from the MessageBird Dashboard (not the Test key). Regenerate the key if necessary.
  1. Error: The originator is incorrect (Code: 9)
  • Cause: The MESSAGEBIRD\_ORIGINATOR is invalid, not registered with MessageBird, or not suitable for the destination country (e.g., using an Alphanumeric ID where a VMN is required for MMS).
  • Solution: Verify the originator value in .env. For MMS in US/Canada, ensure you are using a purchased MessageBird Virtual Mobile Number with MMS support, not an Alphanumeric Sender ID. Check the number's capabilities in the MessageBird Dashboard.
  1. Error: recipient is invalid (Code: 21)
  • Cause: The recipient phone number is incorrectly formatted or not a valid mobile number.
  • Solution: Ensure the recipient number is in E.164 format (+[country code][number]). Validate the number format in your code before calling the API.
  1. Error: Media URL is unreachable or timeout errors
  • Cause: MessageBird cannot fetch the media from the provided mediaUrl within the 5-second timeout. This can be due to:
  • The URL is not publicly accessible (localhost, private network, behind authentication).
  • The server hosting the media is slow or unresponsive.
  • The URL is incorrect or points to a non-existent resource.
  • Solution: Verify the mediaUrl is fully public. Test it in a browser or using curl. Use a CDN or optimized storage (e.g., AWS S3, Google Cloud Storage, Azure Blob Storage) with fast response times. Ensure the media file is served with correct MIME types and headers.
  1. MMS not rendering correctly or received as SMS with a link
  • Cause: Some mobile carriers or devices do not fully support MMS or have restrictions on media formats/sizes. Older devices may fallback to SMS.
  • Solution: Test with multiple carriers and devices in your target market. Ensure media files are within size limits (1MB) and use widely supported formats (JPEG, PNG for images). Some carriers automatically convert MMS to a web link viewable in a browser.
  1. Error: Insufficient balance (Code: 25)
  • Cause: Your MessageBird account does not have enough credit to send the MMS.
  • Solution: Top up your MessageBird account balance via the Dashboard.
  1. Geographic restrictions - MMS failing for non-US/Canada recipients
  • Cause: MessageBird MMS is only available for the US and Canada.
  • Solution: If targeting other countries, you must use a different provider or MessageBird's standard SMS (without media, or use SMS with a shortened link to the media hosted on your server/CDN).
  • MessageBird MMS API Documentation
  • MessageBird Node.js SDK on GitHub
  • E.164 Phone Number Format Guide
  • US 10DLC SMS Registration Guide

Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)

If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.

curl -X POST https://api.sendsmsnokyc.com/messages \
  -H "x-api-key: $SMSROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["+14155551234"],
    "channel": ["sms"],
    "body": "Your verification code is 482910"
  }'
  • Instant onboarding: No KYC paperwork or sales queues β€” grab an API key and fund with crypto (BTC/USDT) or card.
  • Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
  • Transparent global pricing: Compare exact per-country termination rates on our live pricing page.

Ship Global SMS in One API Call

Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.

Explore SMSRoute Developers β†’