code examples

Sent logo
Sent TeamMay 3, 2025 / code examples / Article

How to Send MMS with MessageBird in Next.js: Complete Guide (2025)

Learn how to send MMS messages with MessageBird API in Next.js. Step-by-step tutorial covering setup, implementation, A2P 10DLC compliance, and production deployment.

Learn how to send MMS messages with MessageBird in your Next.js application. This comprehensive tutorial shows you how to build a production-ready MMS messaging system using the MessageBird API, covering everything from initial setup to deployment with A2P 10DLC compliance.

Create a robust Next.js API endpoint (/api/send-mms) that accepts recipient details, message content, and media URLs, then sends MMS messages via MessageBird.

Target Audience: Developers familiar with Next.js and JavaScript/TypeScript who want to integrate messaging APIs. Understand REST APIs and environment variables.

Key Technologies:

  • Next.js: React framework with API routes for backend logic
  • MessageBird API: Communication platform REST API for MMS
  • Node.js: Runtime environment for Next.js
  • (Optional) Postman/curl: For testing your API endpoint

Prerequisites:

  1. Node.js and npm/yarn: Installed on your machine (verify: node -v, npm -v)
  2. MessageBird Account: Register at MessageBird.com
  3. MessageBird Live API Key: Obtain from your Developer Dashboard
  4. MMS-Enabled Virtual Mobile Number (VMN): Critical: MessageBird MMS only supports US and Canada. You need a dedicated, MMS-enabled US or Canadian virtual number as the originator. Standard alphanumeric senders or non-MMS numbers will not work.
  5. A2P 10DLC Registration (US Required): Mandatory as of February 1, 2025. All businesses sending SMS/MMS to US 10-digit long codes must register with A2P 10DLC. Carriers block unregistered numbers. Registration requires:
    • Brand Registration: Submit business tax ID/EIN (1–3 days typically)
    • Campaign Registration: Document opt-in methods and use cases (3–7 business days typically)
    • The Campaign Registry (TCR): Central database for all registrations
    • Industry restrictions: Cannabis, firearms, and payday loans are ineligible
    • Action required: Complete through your MessageBird account before sending production traffic

What You'll Build: MMS Messaging with MessageBird

Goal: Create a secure Next.js API endpoint (/api/send-mms) that accepts MMS parameters (recipient number, subject, body, media URLs) and sends messages via MessageBird.

Problem Solved: Provides a backend mechanism to programmatically send rich media messages to US and Canada users, abstracting MessageBird API interactions into a reusable internal endpoint.

System Architecture:

mermaid
graph LR
    A[Client/Frontend] -- POST /api/send-mms --> B(Next.js API Route);
    B -- Send MMS Request --> C(MessageBird MMS API);
    C -- MMS Sent Confirmation --> B;
    B -- API Response (Success/Error) --> A;
  1. Your client (frontend form or backend service) sends a POST request to /api/send-mms with MMS details
  2. The API route validates the request and retrieves credentials (API Key, Originator Number) from environment variables
  3. The API route constructs and sends a POST request to https://rest.messagebird.com/mms
  4. MessageBird processes the request and returns success (with message details) or failure (with error details)
  5. The API route forwards the appropriate response back to your client

Final Outcome: A functional /api/send-mms endpoint ready for integration and deployment.

Setting Up Your Next.js Project for MessageBird MMS

Initialize a new Next.js project and configure the basic structure and environment.

Step 1: Create a New Next.js App

Open your terminal and run the following command. Choose your preferred settings when prompted (e.g., TypeScript: No, ESLint: Yes, Tailwind CSS: No, src/ directory: No, App Router: No (we'll use Pages Router for API routes simplicity in this guide), import alias: defaults).

bash
npx create-next-app@latest messagebird-mms-sender

Note on Next.js 15 and App Router: This guide uses the Pages Router (pages/api/*) for simplicity and broad compatibility. However, Next.js 15 defaults to the App Router, which is now the recommended approach for new projects. If you're using App Router:

  • Instead of pages/api/send-mms.js, create app/api/send-mms/route.ts (or .js)
  • Use Web Standard Request/Response APIs instead of Node.js request/response objects
  • Export named functions: export async function POST(request: Request) { ... }
  • Access request body via: await request.json()
  • Return responses using: return Response.json({ data }, { status: 200 })
  • The core MessageBird integration logic remains identical

For this tutorial, we continue with Pages Router as it provides a more straightforward learning path for API-focused implementations.

Step 2: Navigate to Project Directory

bash
cd messagebird-mms-sender

Step 3: Set up Environment Variables

Create a file named .env.local in the root of your project. This file securely stores your MessageBird credentials and should not be committed to version control.

bash
touch .env.local

Add the following lines to .env.local, replacing the placeholder values later:

dotenv
# .env.local

# Obtain from MessageBird Dashboard -> Developers -> API access -> Live API Key
MESSAGEBIRD_API_KEY=YOUR_LIVE_API_KEY

# Your purchased/configured MMS-enabled US/CA Virtual Mobile Number (E.164 format)
# Obtain from MessageBird Dashboard -> Numbers
MESSAGEBIRD_ORIGINATOR=+1XXXXXXXXXX

Step 4: Add .env.local to .gitignore

Ensure that your .gitignore file (which should exist by default) includes .env.local to prevent accidentally committing secrets. It should already contain a line like:

text
# .gitignore (ensure this line is present)
.env*.local

Step 5: (Optional) Install Development Dependencies

While Next.js's built-in fetch is sufficient, you might prefer axios for API calls. This is optional.

bash
npm install axios
# or
yarn add axios

Project Structure:

Your relevant project structure should look like this:

messagebird-mms-sender/ ├── pages/ │ ├── api/ │ │ └── # Create your API route here (e.g., send-mms.js) │ ├── _app.js │ └── index.js ├── public/ ├── styles/ ├── .env.local # Your secret credentials ├── .gitignore ├── next.config.js ├── package.json └── README.md

Architectural Decisions:

  • API Routes: Use Next.js API routes (pages/api) to handle backend logic directly within the Next.js application. This avoids needing a separate server for this functionality.
  • Environment Variables: Store secrets like API keys and originator numbers in .env.local for security and configuration management.
  • Pages Router: Chosen for simplicity in setting up a basic API endpoint compared to the App Router for this specific use case.

Implementing the MessageBird MMS API in Next.js

Create the core API endpoint that handles MMS message sending.

Step 2.1: Create the API Route File

Create pages/api/send-mms.js.

Step 2.2: Import Dependencies

javascript
// pages/api/send-mms.js
import messagebird from 'messagebird';

Import the MessageBird SDK to interact with the API.

Step 2.3: Initialize the MessageBird Client

javascript
const client = messagebird(process.env.MESSAGEBIRD_ACCESS_KEY);

Initialize your MessageBird client using the Access Key from your environment variables. This client handles authentication and API communication.

Step 2.4: Implement the API Handler

javascript
export default async function handler(req, res) {
  // Only accept POST requests
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method Not Allowed' });
  }

  const { to, body, mediaUrls } = req.body;

  // Validate required fields
  if (!to || !body) {
    return res.status(400).json({ error: 'Missing required fields: to, body' });
  }

  // Validate E.164 format (simplified)
  if (!/^\+[1-9]\d{1,14}$/.test(to)) {
    return res.status(400).json({
      error: 'Invalid phone number format. Use E.164 format (e.g., +1234567890)'
    });
  }

  try {
    // Send MMS via MessageBird
    const result = await new Promise((resolve, reject) => {
      client.messages.create({
        originator: process.env.MESSAGEBIRD_ORIGINATOR, // Your sender ID
        recipients: [to],
        body: body,
        mediaUrls: mediaUrls || [], // Optional media attachments
      }, (err, response) => {
        if (err) reject(err);
        else resolve(response);
      });
    });

    return res.status(200).json({
      success: true,
      messageId: result.id,
      message: 'MMS sent successfully'
    });
  } catch (error) {
    console.error('MessageBird Error:', error);
    return res.status(500).json({
      error: 'Failed to send MMS',
      details: error.errors || error.message
    });
  }
}

Your handler:

  • Accepts only POST requests
  • Validates recipient phone numbers in E.164 format
  • Sends MMS with optional media attachments
  • Returns structured success/error responses
  • Logs errors for debugging

Building the Complete MMS API Endpoint

The code in the previous section already establishes the core API layer using Next.js API routes. This section refines the documentation and testing aspects.

API Endpoint: POST /api/send-mms

Authentication: Currently, this endpoint relies on the security of your Next.js deployment environment. If this endpoint needs to be accessed from untrusted clients (e.g., a public frontend), implement an authentication/authorization layer before the MessageBird logic executes. This guide assumes the endpoint is called from a trusted backend or a secured frontend. Common strategies include validating bearer tokens (JWTs, API keys) using middleware, checking session cookies, or implementing OAuth flows depending on the client.

Request Validation: Basic validation is included. Libraries like zod or joi can be added for more complex schema validation if needed.

API Endpoint Documentation:

  • Method: POST

  • URL: /api/send-mms

  • Headers:

    • Content-Type: application/json
  • Request Body (JSON):

    json
    {
      "recipient": "+15551234567",
      "subject": "Check this out!",
      "body": "Here's the logo we discussed.",
      "mediaUrls": [
        "https://www.example.com/images/logo.png",
        "https://www.example.com/docs/info.pdf"
      ]
    }
    • recipient (string, required): E.164 formatted US/CA number.
    • subject (string, optional): Max 256 chars.
    • body (string, optional): Max 2000 chars. Required if mediaUrls is empty.
    • mediaUrls (array of strings, optional): Array of public URLs. Required if body is empty. Max 10 URLs. Max 1 MB each.
  • Success Response (200 OK):

    json
    {
      "success": true,
      "messageId": "efa6405d518d4c0c88cce11f7db775fb",
      "data": {
        "id": "efa6405d518d4c0c88cce11f7db775fb",
        "href": "https://rest.messagebird.com/mms/efa6405d518d4c0c88cce11f7db775fb",
        "direction": "mt",
        "originator": "+1XXXXXXXXXX",
        "subject": "Check this out!",
        "body": "Here's the logo we discussed.",
        "reference": null,
        "mediaUrls": [
          "https://www.example.com/images/logo.png",
          "https://www.example.com/docs/info.pdf"
        ],
        "scheduledDatetime": null,
        "createdDatetime": "2024-04-20T10:00:00+00:00",
        "recipients": {
          "totalCount": 1,
          "totalSentCount": 1,
          "totalDeliveredCount": 0,
          "totalDeliveryFailedCount": 0,
          "items": [
            {
              "recipient": 15551234567,
              "status": "sent",
              "statusDatetime": "2024-04-20T10:00:00+00:00"
            }
          ]
        }
      }
    }
  • Error Response (4xx/5xx):

    json
    // Example: 400 Bad Request (Missing recipient)
    {
      "message": "Missing required field: recipient"
    }
    json
    // Example: 401 Unauthorized (Invalid API Key from MessageBird, passed through)
    {
        "message": "Authentication failed",
        "details": {
            "errors": [
                {
                    "code": 2,
                    "description": "Authentication failed",
                    "parameter": null
                }
            ]
        }
    }
    json
    // Example: 500 Internal Server Error (Network issue)
    {
        "message": "Internal Server Error while contacting MessageBird.",
        "details": "fetch failed"
    }

Testing with curl:

Replace placeholders with your actual data. Run this from your terminal while your Next.js development server is running (npm run dev or yarn dev).

bash
curl -X POST http://localhost:3000/api/send-mms \
-H "Content-Type: application/json" \
-d '{
  "recipient": "+1RECIPIENT_PHONE_NUMBER",
  "subject": "Test MMS from Next.js",
  "body": "This is a test message with an image.",
  "mediaUrls": ["https://developers.messagebird.com/img/logos/mb-400.jpg"]
}'

Ensure the mediaUrls points to a publicly accessible image or file meeting MessageBird's criteria (under 1 MB, accessible within 5 seconds).

Configuring MessageBird API Credentials

This section focuses on obtaining and managing the necessary MessageBird credentials.

Step 1: Obtain Live API Key

  1. Log in to your MessageBird Dashboard.
  2. Navigate to Developers in the left-hand sidebar.
  3. Click on API access.
  4. Under the Live API Key section, click Show key.
  5. Copy this key carefully.
  6. Paste this value into your .env.local file for the MESSAGEBIRD_API_KEY variable.
    dotenv
    # .env.local
    MESSAGEBIRD_API_KEY=live_xxxxxxxxxxxxxxxxxxxxxxxxxxxx

Step 2: Obtain and Verify MMS-Enabled Originator Number

  1. In the MessageBird Dashboard, navigate to Numbers in the left-hand sidebar.
  2. If you don't have a US or Canadian number, buy one that supports MMS. Look for numbers with MMS capability explicitly listed.
  3. Once you have a suitable number, ensure it's configured for MMS. This might involve specific setup steps depending on the number type and regulations. Consult MessageBird documentation or support if needed. This is a critical step. Note that acquiring and using US/CA numbers for programmatic messaging, especially MMS, often involves compliance steps like A2P 10DLC registration in the US. Investigate MessageBird's specific requirements and processes for this.
  4. Copy the number in E.164 format (e.g., +12015550123).
  5. Paste this value into your .env.local file for the MESSAGEBIRD_ORIGINATOR variable.
    dotenv
    # .env.local
    MESSAGEBIRD_ORIGINATOR=+12015550123

Handling API Keys and Secrets Securely:

  • NEVER commit .env.local or any file containing your API key or sensitive numbers to version control (Git).
  • Use environment variables provided by your deployment platform (Vercel, Netlify, AWS, etc.) in production environments. Do not place a .env.local file directly on a production server.
  • Restrict access to your MessageBird account and API keys. Regenerate keys if you suspect they have been compromised.

Fallback Mechanisms:

For this simple sending endpoint, a direct fallback isn't implemented. In a more complex system, you might consider:

  • Retry Logic: Implement retries with exponential backoff specifically for potentially transient network errors or specific MessageBird error codes (like 5xx errors). (See Section 5).
  • Alternative Providers: If high availability is critical, you could abstract the sending logic further to switch to a different MMS provider if MessageBird experiences an extended outage, but this significantly increases complexity.

Environment Variable Summary:

  • MESSAGEBIRD_API_KEY:
    • Purpose: Authenticates your requests with the MessageBird API.
    • Format: String starting with live_ followed by alphanumeric characters.
    • How to Obtain: MessageBird Dashboard -> Developers -> API access.
  • MESSAGEBIRD_ORIGINATOR:
    • Purpose: The dedicated US/CA virtual mobile number (sender ID) enabled for MMS sending.
    • Format: E.164 string (e.g., +1XXXXXXXXXX).
    • How to Obtain: MessageBird Dashboard -> Numbers. Must be a number you own/rent that is explicitly MMS-enabled for US/CA destinations.

Error Handling and Retry Logic for MMS Messages

Our API route includes basic error handling. This section discusses refinements.

Consistent Error Handling Strategy:

  • Client Errors (4xx): Return 400 for bad request data (missing fields, invalid formats). Return 405 for incorrect HTTP methods. Return 401/403 if implementing authentication and it fails.
  • Server/Upstream Errors (5xx): Return 500 for internal server errors (e.g., missing environment variables, unexpected exceptions). Return the status code provided by MessageBird (often 4xx or 5xx mapped to our 502/503/500) if the error originates from their API, providing their error details in the response body for debugging.
  • Logging: Log detailed error information on the server-side (Next.js console or a dedicated logging service) for all 5xx errors and potentially for 4xx errors if useful for debugging patterns. Do not expose excessive internal details (like stack traces) in the client response for 5xx errors.

Logging:

The current implementation uses console.error. For production:

  • Structured Logging: Use libraries like pino or winston to output logs in JSON format, making them easier to parse by log management systems (e.g., Datadog, Logtail, Sentry).
  • Log Levels: Implement different log levels (DEBUG, INFO, WARN, ERROR) to control verbosity. Log successful sends at INFO, client errors at WARN, and server/MessageBird errors at ERROR.
  • Context: Include contextual information in logs, like a request ID, user ID (if applicable), and relevant parts of the request/response causing the error.

Example using console (Simplified Structured):

javascript
// Inside the catch block for MessageBird API errors
console.error(JSON.stringify({
    timestamp: new Date().toISOString(),
    level: 'ERROR',
    message: 'MessageBird API Error',
    statusCode: response.status,
    details: responseData,
    apiKeyUsed: apiKey ? `${apiKey.substring(0, 5)}...` : 'MISSING', // Mask API Key
    originatorUsed: originator || 'MISSING',
    requestBody: { recipient: 'REDACTED', subject: 'REDACTED', body: 'REDACTED', mediaUrls } // CAUTION: Logging PII. Mask or omit sensitive fields.
}));

// Inside the general catch block
console.error(JSON.stringify({
    timestamp: new Date().toISOString(),
    level: 'ERROR',
    message: 'Internal Server Error while contacting MessageBird.',
    error: error.message,
    stack: error.stack // Optional, might be verbose
}));

Note: Be cautious about logging sensitive data like recipient numbers, subject lines, or body content in production. Redact or omit PII.

Retry Mechanisms:

Direct retries for user-initiated API calls can be tricky (risk of duplicate sends). A better place for retries is often for background jobs. However, if needed for transient network issues:

  • Identify Retryable Errors: Only retry on specific conditions, like network errors (fetch failing) or 5xx errors from MessageBird that indicate a temporary issue (e.g., 503 Service Unavailable). Do not retry on 4xx errors (bad input, invalid key) as they won't succeed without changes.
  • Exponential Backoff: Use libraries like async-retry or implement manually. Start with a short delay (e.g., 100 ms) and double it for each retry attempt, up to a maximum number of retries (e.g., 3–5).
  • Idempotency: If implementing retries, ensure the downstream API (MessageBird) handles potentially duplicate requests gracefully, or use the reference field in the MessageBird payload to generate a unique identifier for the request that MessageBird might use for deduplication (check their specific documentation on idempotency).

Testing Error Scenarios:

  • Invalid API Key: Temporarily change MESSAGEBIRD_API_KEY in .env.local to an invalid value and make a request. Expect a 401/500 response with an authentication error message.
  • Missing Originator: Remove MESSAGEBIRD_ORIGINATOR from .env.local. Expect a 500 server configuration error.
  • Invalid Originator: Use a number not enabled for MMS or an alphanumeric string. Expect an error from MessageBird (likely a 4xx error passed through as 5xx).
  • Missing Recipient: Send a request without the recipient field. Expect a 400 Bad Request.
  • Missing Body/Media: Send a request with neither body nor mediaUrls. Expect a 400 Bad Request.
  • Invalid Media URL: Use a non-existent or private URL in mediaUrls. Expect an error from MessageBird related to fetching the media.
  • Network Interruption: (Harder to test locally) Simulate network failure during the fetch call if possible, or add temporary code to throw an error before the fetch. Expect a 500 Internal Server Error.

Optional: Tracking MMS Message Status with a Database

For the core functionality of sending a single MMS, a database is not strictly required by this API endpoint itself. The messageId returned by MessageBird can be logged or returned to the client, which might store it elsewhere.

However, if you were building a system that needed to track message status, manage conversations, or store message history, add a database.

Potential Schema (if tracking messages):

sql
-- Example PostgreSQL Schema
CREATE TABLE sent_mms_messages (
    id SERIAL PRIMARY KEY,                     -- Internal DB ID
    messagebird_id VARCHAR(255) UNIQUE NOT NULL, -- ID from MessageBird API response
    recipient VARCHAR(20) NOT NULL,
    originator VARCHAR(20) NOT NULL,
    subject TEXT,
    body TEXT,
    media_urls TEXT[],                         -- Array of URLs sent
    reference VARCHAR(255),                    -- Client reference sent to MessageBird
    status VARCHAR(50) NOT NULL DEFAULT 'sent',-- Initial status from MessageBird response
    status_last_updated_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    messagebird_created_at TIMESTAMPTZ          -- createdDatetime from MessageBird response
);

CREATE INDEX idx_messagebird_id ON sent_mms_messages(messagebird_id);
CREATE INDEX idx_recipient ON sent_mms_messages(recipient);
CREATE INDEX idx_status ON sent_mms_messages(status);

Implementation (Conceptual):

  1. Choose Database & ORM: Select a database (PostgreSQL, MySQL, MongoDB) and potentially an ORM (like Prisma, TypeORM, Sequelize) for easier interaction.
  2. Define Schema: Create the table schema (as above) using SQL or ORM migration tools (e.g., prisma migrate dev).
  3. Data Access Layer: Create functions or methods to interact with the database (e.g., saveSentMessage, updateMessageStatus).
  4. Integration: In the /api/send-mms route, after receiving a successful response from MessageBird, call your saveSentMessage function to store the relevant details (messagebird_id, recipient, status, etc.) in the database before returning the 200 OK response to the client.
  5. Status Updates: You would need a separate webhook endpoint (see MessageBird docs on "Handle a status report") to receive status updates from MessageBird and use those to call updateMessageStatus in your database.

This guide focuses only on sending, so database implementation is omitted for brevity.

Securing Your MMS API Endpoint

Security is paramount when dealing with APIs and potentially user data.

  • Input Validation and Sanitization:

    • Validation: Already discussed basic validation. Add stricter checks:
      • Use regex or a library like libphonenumber-js to validate E.164 format for recipient.
      • Enforce length limits on subject and body.
      • Validate mediaUrls are actual URLs (basic regex or new URL()) and check the array length (max 10).
    • Sanitization: While not directly displaying input here, if subject or body were ever stored and displayed elsewhere, sanitize them against Cross-Site Scripting (XSS) using libraries like dompurify (if rendering in HTML) or appropriate encoding/escaping based on the context. For sending via API, ensure content adheres to MessageBird's policies.
  • Authentication/Authorization: (As mentioned in Section 3) Critical if the endpoint is not purely for internal backend use. Implement robust auth to ensure only authorized clients can trigger MMS sends. This often involves middleware in your Next.js API route to validate credentials like JWTs, session tokens, or API keys before executing the core logic.

  • Protecting API Keys: Already covered via environment variables and .gitignore.

  • Rate Limiting:

    • Infrastructure Level: Deployment platforms like Vercel often have built-in rate limiting per IP address.
    • Application Level: For more granular control (e.g., per user ID or API key), implement rate limiting within the API route itself. Use libraries like rate-limiter-flexible or upstash/ratelimit (requires Redis/Upstash). This prevents abuse and controls costs.
      javascript
      // Conceptual example using a hypothetical rate limiter library
      import { RateLimiterMemory } from 'rate-limiter-flexible';
      
      const rateLimiter = new RateLimiterMemory({
        points: 10, // Number of points
        duration: 60, // Per second(s)
      });
      
      export default async function handler(req, res) {
          // Use a stable identifier: IP address (less reliable behind proxies) or user ID/API key if authenticated
          const clientIdentifier = req.headers['x-forwarded-for']?.split(',')[0].trim() || req.socket.remoteAddress; // Basic IP identification
          // If authenticated: const clientIdentifier = req.userId || req.apiKeyId;
      
          try {
              await rateLimiter.consume(clientIdentifier); // Consume 1 point per request
          } catch (rejRes) {
              // Log rate limit exceeded event if desired
              return res.status(429).json({ message: "Too Many Requests" });
          }
      
          // ... rest of the API logic
      }
  • Common Vulnerabilities:

    • SSRF (Server-Side Request Forgery): Although we control the target URL (messagebird.com), ensure no user input directly forms parts of other internal or external requests made by the server.
    • Injection: Not directly applicable here as we're sending data to a structured API, but always sanitize inputs if they were used in database queries (ORMs help prevent SQL injection) or shell commands.
  • Testing for Vulnerabilities:

    • Use security scanners (like OWASP ZAP) against your deployed application.
    • Perform code reviews focusing on security aspects (input handling, auth, dependencies).
    • Test authentication/authorization bypass attempts.
    • Test rate limiting by sending rapid requests.

MessageBird MMS Requirements and Limitations

  • E.164 Number Formatting: MessageBird requires recipients in E.164 format (+ followed by country code and number, e.g., +15551234567). Ensure your frontend or backend logic correctly formats numbers before sending them to this API endpoint. The originator number must also be in this format.
  • Character Limits:
    • subject: 256 characters. Truncate or validate before sending.
    • body: 2000 characters. Truncate or validate.
  • Media URL Constraints:
    • Public Accessibility: URLs must be publicly accessible without authentication. MessageBird's servers need to fetch them.
    • Timeout: MessageBird attempts to fetch media within 5 seconds. Ensure files are hosted on performant storage.
    • Size Limits (2025 Current):
      • Total message size: Maximum 900 KB including all attachments
      • Per-attachment size: Maximum 600 KB after resizing
      • Automatic resizing: Bird (MessageBird) supports automatic resizing for images and GIFs up to 5 MB original size, reducing them to meet delivery requirements
      • If a file exceeds limits and cannot be resized, you'll receive an UNSUPPORTED_MEDIA_TYPE: 14004 error
    • Count Limit: Maximum 10 mediaUrls per message.
    • Supported Types: Refer to the MessageBird documentation (e.g., https://developers.messagebird.com/api/mms-messaging/) for the extensive list of supported audio/*, video/*, image/*, text/*, and application/pdf types. Common formats include JPEG, PNG, GIF for images. Sending unsupported types will result in an UNSUPPORTED_MEDIA_TYPE error.
  • Country Limitations: Currently, MessageBird MMS sending is restricted to US and Canada recipients using a US or Canadian MMS-enabled VMN as the originator. Attempts to send elsewhere or with an invalid originator type will fail. Your application logic should reflect this limitation.
  • VMN Requirement: A standard phone number or alphanumeric sender ID cannot be used as the originator for MMS. It must be the specific VMN purchased/configured for MMS.
  • Time Zones: The scheduledDatetime parameter, if used, requires RFC3339 format including the timezone offset (e.g., YYYY-MM-DDTHH:mm:ssP, like 2025-12-31T18:00:00-05:00 or 2025-12-31T23:00:00Z).

Optimizing MMS Delivery Performance

For this specific API endpoint, performance is largely dictated by the latency of the MessageBird API itself and the time taken for MessageBird to fetch media URLs.

  • Media Hosting: Host mediaUrls content on a fast, reliable CDN or object storage (like AWS S3, Google Cloud Storage) close to MessageBird's infrastructure if possible, to minimize fetch times and timeouts.
  • Asynchronous Processing: If the client calling /api/send-mms doesn't need an immediate confirmation that MessageBird sent the MMS, you could make the endpoint respond faster:
    1. Receive the request at /api/send-mms.
    2. Perform initial validation.
    3. Push the validated MMS details onto a queue (e.g., Redis queue, AWS SQS, Google Cloud Tasks).
    4. Immediately return a 202 Accepted response to the client, indicating the request is queued for processing.
    5. Have a separate background worker process (another serverless function, a dedicated Node.js process) that pulls jobs from the queue and makes the actual call to the MessageBird API. This worker would handle retries and logging related to the MessageBird interaction. This decouples the client request from the potentially slower third-party API call.
  • Connection Pooling: If using a library like axios and making many requests, ensure keep-alive connections are utilized effectively (often handled by default in Node.js fetch and modern axios).
  • Payload Size: Keep request payloads minimal by only sending necessary data.
  • Next.js Optimizations: Ensure your Next.js application itself is optimized (code splitting, efficient dependencies), although this has less direct impact on the API route's interaction with the external service.

For more information on building messaging applications with Node.js and Next.js, explore these related topics:

  • SMS Messaging: Learn how to implement basic SMS sending with MessageBird in Next.js
  • A2P 10DLC Registration: Complete guide to registering your business for A2P 10DLC compliance
  • Next.js API Routes: Deep dive into building robust API endpoints in Next.js
  • MessageBird Webhooks: Set up delivery status callbacks and inbound message handling

These resources will help you expand your messaging implementation beyond basic MMS sending.

Frequently Asked Questions

How to send MMS messages with MessageBird and Next.js?

Create a Next.js API route that handles POST requests to /api/send-mms. This route should interact with the MessageBird API using your API key and an MMS-enabled virtual number. The API route will receive recipient details, message content, and media URLs, then forward this information to MessageBird to send the MMS message.

What is the MessageBird API used for in this Next.js project?

The MessageBird API is the core communication platform for sending SMS, MMS, and other message types. This specific project uses their REST API for sending MMS messages, allowing your Next.js application to programmatically send rich media messages.

Why does MessageBird require a US or Canadian number for MMS?

MessageBird currently limits MMS sending to the US and Canada. Therefore, you need a dedicated, MMS-enabled US or Canadian virtual mobile number (VMN) as the message originator. Standard alphanumeric senders or non-MMS-enabled numbers won't work.

When should I use environment variables for my API key?

Always store sensitive credentials like API keys in environment variables, especially the `MESSAGEBIRD_API_KEY` and `MESSAGEBIRD_ORIGINATOR`. This protects your keys from being exposed in your codebase and simplifies configuration across different environments.

Can I send MMS messages internationally with this setup?

No, the provided setup and MessageBird's current capabilities restrict MMS sending to the US and Canada. You'll need an alternative solution or provider for international MMS.

How to structure a Next.js API route for sending MMS?

The API route should handle POST requests, validate incoming data, retrieve credentials from environment variables, construct the MessageBird API payload, and send the request to MessageBird. It should also handle the MessageBird response and return appropriate success or error messages to the client.

What is the required format for recipient phone numbers?

MessageBird requires recipient phone numbers to be in E.164 format. This format includes a plus sign (+) followed by the country code and phone number, such as +15551234567 for a US number.

Why is input validation important for a MessageBird MMS API?

Input validation is crucial for security and preventing errors. It protects against malformed requests, ensures compliance with MessageBird's API requirements (like character limits), and prevents accidental misuse or abuse of the service.

How do I handle MessageBird API errors in my Next.js app?

Implement robust error handling within the API route by checking response status codes and parsing error messages from the MessageBird API response. Log errors on the server-side, providing sufficient detail for debugging, and return appropriate error responses to the client.

What is the maximum number of media URLs I can send in an MMS?

MessageBird limits the number of media URLs to a maximum of 10 per MMS message. Each media file should also be under 1MB and publicly accessible via its URL.

How to test my MessageBird MMS integration in Next.js?

Use tools like `curl` or Postman to send POST requests to your local development server's /api/send-mms endpoint. Test different scenarios, including valid and invalid input data, to ensure proper functionality and error handling.

What are the best practices for hosting media files for MMS messages?

For optimal performance and reliability, host media files on a Content Delivery Network (CDN) or fast, reliable object storage like AWS S3 or Google Cloud Storage. Ensure the files are publicly accessible and have a fast response time to prevent MessageBird timeouts.

How to secure my Next.js API route for sending MMS messages?

Implement authentication and authorization mechanisms if the endpoint is exposed to untrusted clients. Use environment variables for API keys, validate and sanitize all input data, implement rate limiting to prevent abuse, and be mindful of common vulnerabilities like SSRF.

What are the character limits for the MMS subject and body?

The `subject` field has a maximum length of 256 characters, while the `body` field allows up to 2000 characters. Your application should validate or truncate these fields accordingly before sending the request to MessageBird.