How to Send MMS with Node.js and Vonage Messages API (2025 Guide)
Learn how to send MMS messages with images using Node.js, Express, and Vonage Messages API. Step-by-step tutorial with code examples, authentication setup, webhook configuration, and troubleshooting for multimedia messaging.
Multimedia Messaging Service (MMS) enables sending messages that include media like images, GIFs, or videos, offering richer communication than standard SMS. This guide walks you through building a Node.js application using the Express framework to send MMS messages via the Vonage Messages API.
You'll build an Express API endpoint that accepts a recipient phone number and an image URL, then uses the Vonage Node.js SDK to send an MMS message. This guide covers everything from project setup and Vonage configuration to implementation, error handling, and testing.
Goal: Build a robust Node.js service capable of sending MMS messages reliably using Vonage.
Technology Stack (Verified January 2025):
- Node.js: JavaScript runtime environment for server-side development (v22.x LTS recommended as of January 2025; v20.x in maintenance mode).
- Express: Minimal and flexible Node.js web application framework used to create the API endpoint.
- Vonage Messages API: Unified API for sending messages across various channels, including MMS, SMS, WhatsApp, and RCS. Supports multi-channel failover introduced in Q3 2025.
- Vonage Node.js SDK (
@vonage/messages): Official library for interacting with the Vonage Messages API in Node.js applications (v1.20.3 as of January 2025). - dotenv: Module to load environment variables from a
.envfile. - ngrok (Optional but Recommended for Development): Tool to expose local servers to the internet for testing webhooks.
MMS Technical Specifications (January 2025):
- Supported Image Formats: JPEG/JPG, PNG (recommended for lossless quality), GIF (including animated)
- File Size Limits:
- Recommended maximum: 500 KB for reliable delivery across all carriers
- Most US/Canadian carriers: up to 1 MB supported
- AWS limit: 2 MB maximum
- Best practice for time-sensitive campaigns: 150 KB or less
- Optimal Image Dimensions: 9:16 aspect ratio (1080×1920 px or 640×1138 px) for mobile viewing
- Supported From US Numbers: 10DLC, Toll-Free, and Short Code numbers to US/Canadian recipients
- Video Formats: MP4 or 3GP
- Audio Formats: MP3
System Architecture:
The system follows this flow:
- A client (e.g., Postman, curl, another application) sends an HTTP POST request to the Node.js / Express API endpoint.
- The Express application validates the request and uses the Vonage Node.js SDK (authenticated with API credentials and application details) to send an MMS request to the Vonage Messages API.
- The Vonage Messages API handles the delivery of the MMS message to the recipient's mobile device.
- Vonage sends status updates (e.g., delivery receipts) back to a configured Webhook URL (which might be an ngrok tunnel during development) handled by the Express application.
- The Express application sends an API response back to the original client.
Prerequisites:
- Vonage API Account: Sign up for a free Vonage account if you don't have one. You'll get some free credits to start.
- Vonage API Key and Secret: Find these at the top of your Vonage API Dashboard.
- Vonage US Number (MMS Capable): Purchase a US-based virtual number capable of sending SMS and MMS. You can do this via the Vonage Dashboard (Numbers > Buy Numbers). MMS sending via Vonage is primarily supported from US 10DLC, Toll-Free, or Short Code numbers to US/Canadian recipients.
- Node.js and npm (or yarn): Install Node.js v22.x LTS (recommended as of January 2025) or v20.x (maintenance mode). Download from nodejs.org. Note: Node.js v18.x reached end-of-life on April 30, 2025 and is no longer supported.
- ngrok (Optional): Download and set up ngrok if you need to test webhook functionality locally. ngrok.com. A free account is sufficient.
- Basic Understanding: Familiarity with JavaScript, Node.js, REST APIs, and terminal/command line usage.
1. Setting Up the Node.js Project
Create the project directory, initialize Node.js, and install the necessary dependencies.
-
Create Project Directory: Open your terminal or command prompt and create a new directory for your project, then navigate into it.
bashmkdir vonage-mms-sender cd vonage-mms-sender -
Initialize Node.js Project: Initialize the project using npm. The
-yflag accepts default settings.bashnpm init -yThis creates a
package.jsonfile. -
Install Dependencies: Install Express for the web server,
@vonage/messagesfor the Vonage SDK, anddotenvfor managing environment variables.bashnpm install express @vonage/messages dotenv --saveexpress: Web framework for creating the API endpoint.@vonage/messages: The correct Vonage SDK specifically for the Messages API (handles SMS, MMS, WhatsApp, etc.). Do not use the older@vonage/server-sdkfor sending MMS via the Messages API.dotenv: Loads environment variables from a.envfile intoprocess.env.
-
Create Project Files: Create the main application file and a file for environment variables.
bashtouch index.js .env .gitignoreindex.js: Contains your Express application code..env: Stores sensitive credentials (API keys, etc.)..gitignore: Specifies files that Git should ignore (like.envandnode_modules).
-
Configure
.gitignore: Addnode_modulesand.envto your.gitignorefile to prevent committing them to version control.text# .gitignore node_modules/ .env private.keyNote: Add
private.keyhere, which you'll generate later.
2. Vonage Account Configuration
Before writing code, configure your Vonage account and application correctly.
-
Get API Key and Secret:
- Log in to your Vonage API Dashboard.
- Your API Key and API Secret are displayed prominently at the top. Copy these – you'll need them for the
.envfile.
-
Purchase a US MMS-Capable Number:
- Navigate to Numbers > Buy Numbers in the dashboard.
- Search for numbers in the USA. Ensure the capabilities include SMS and MMS.
- Purchase a number. Note this number down – it will be your sender number.
-
Set Default SMS API to
Messages API:- This is a crucial step often missed. Go to your Account Settings in the Vonage Dashboard.
- Find the "API Settings" or "SMS Settings" section.
- Ensure the Default SMS setting is set to
Messages API. This determines the format of webhooks and ensures compatibility with the@vonage/messagesSDK. Save the changes.
-
Create a Vonage Application: Vonage Applications act as containers for your communication settings and handle authentication using public/private key pairs for certain APIs like Messages.
- Navigate to Applications > Create a new application.
- Give your application a descriptive name (e.g., "Node MMS Sender").
- Generate Public/Private Key Pair: Click the "Generate public and private key" link. A public key will be added to the form, and a
private.keyfile will be downloaded. Save thisprivate.keyfile securely in your project's root directory (the one containingindex.js). Do not commit this file to Git. - Enable Capabilities: Toggle ON the Messages capability.
- Configure Webhooks: Even though this guide focuses on sending, the Messages API application requires webhook URLs for status updates and inbound messages.
- Status URL: Where Vonage sends delivery receipts and status updates for outgoing messages.
- Inbound URL: Where Vonage sends incoming messages sent to your Vonage number linked to this application.
- For Development: Use ngrok to create temporary public URLs that forward to your local machine. Open a new terminal window and run:
ngrok will provide a forwarding URL (e.g.,bash
# Make sure you are NOT in your project directory for this command ngrok http 3000https://<unique-id>.ngrok.io). Use this URL for your webhooks:- Status URL:
https://<unique-id>.ngrok.io/webhooks/status - Inbound URL:
https://<unique-id>.ngrok.io/webhooks/inbound - Set the HTTP method for both to POST.
- Status URL:
- For Production: Replace the ngrok URLs with your actual, publicly accessible API endpoints designed to handle these webhooks. These endpoints must respond with a
200 OKstatus quickly, otherwise Vonage will retry sending the webhook.
- Click Create application.
-
Note the Application ID: After creating the application, you'll be redirected to its overview page. Copy the Application ID. You'll need this for the
.envfile. -
Link Your Vonage Number: On the application overview page, scroll down to the "Linked numbers" section. Find the US MMS-capable number you purchased earlier and click the Link button next to it. This connects incoming messages and associates outgoing messages sent via this application with that number.
3. Secure Configuration with .env
Store your sensitive credentials and configuration details in the .env file. Never commit this file to version control.
Populate your .env file with the information gathered:
# .env
# Vonage API Credentials (from Dashboard)
VONAGE_API_KEY=YOUR_API_KEY
VONAGE_API_SECRET=YOUR_API_SECRET
# Vonage Application Details (from Application Settings)
VONAGE_APPLICATION_ID=YOUR_APPLICATION_ID
# Path relative to the project root where private.key is stored
VONAGE_PRIVATE_KEY_PATH=./private.key
# Vonage Number (The US MMS number you purchased and linked)
VONAGE_MMS_SENDER_NUMBER=YOUR_VONAGE_US_NUMBER
# Server Port
PORT=3000- Replace the placeholder values (
YOUR_...) with your actual credentials. VONAGE_PRIVATE_KEY_PATH: Ensure this path correctly points to your downloadedprivate.keyfile../private.keyassumes it's in the same directory asindex.js.VONAGE_MMS_SENDER_NUMBER: Use the E.164 format (e.g.,12015550123).
4. Implementing the Express API for Sending MMS
Now, let's write the Node.js code using Express to create an API endpoint for sending MMS.
// index.js
'use strict';
// Load environment variables from .env file
require('dotenv').config();
const express = require('express');
const { Messages, MMSImage } = require('@vonage/messages'); // Use the correct SDK
// --- Vonage Client Initialization ---
// Validate essential environment variables
const requiredEnv = [
'VONAGE_API_KEY',
'VONAGE_API_SECRET',
'VONAGE_APPLICATION_ID',
'VONAGE_PRIVATE_KEY_PATH',
'VONAGE_MMS_SENDER_NUMBER',
];
const missingEnv = requiredEnv.filter(key => !process.env[key]);
if (missingEnv.length > 0) {
console.error(`Error: Missing required environment variables: ${missingEnv.join(', ')}`);
console.error('Please check your .env file.');
process.exit(1); // Exit if configuration is incomplete
}
let vonageMessages;
try {
vonageMessages = new Messages({
apiKey: process.env.VONAGE_API_KEY,
apiSecret: process.env.VONAGE_API_SECRET,
applicationId: process.env.VONAGE_APPLICATION_ID,
privateKey: process.env.VONAGE_PRIVATE_KEY_PATH, // SDK handles reading the file path
});
} catch (initError) {
console.error('Error initializing Vonage Messages SDK:', initError);
console.error('Please check your .env configuration and private key path/permissions.');
process.exit(1);
}
// --- Express Application Setup ---
const app = express();
app.use(express.json()); // Middleware to parse JSON bodies
app.use(express.urlencoded({ extended: true })); // Middleware for URL-encoded bodies
const PORT = process.env.PORT || 3000;
// --- API Endpoint for Sending MMS ---
app.post('/send-mms', async (req, res) => {
console.log('Received /send-mms request:', req.body);
// 1. Basic Input Validation
const { recipientNumber, imageUrl, caption } = req.body;
if (!recipientNumber || !imageUrl) {
return res.status(400).json({
success: false,
message: 'Missing required fields: recipientNumber and imageUrl',
});
}
// Basic validation: checks if it's digits after removing optional leading '+'. E.164 format is recommended for the 'to' field.
if (!/^\d+$/.test(recipientNumber.replace(/^\+/, ''))) {
return res.status(400).json({
success: false,
message: 'Invalid recipientNumber format. Please provide digits only (optionally starting with +). E.164 format is recommended.',
});
}
// Basic validation for image URL format
try {
new URL(imageUrl);
} catch (error) {
return res.status(400).json({
success: false,
message: 'Invalid imageUrl format.',
});
}
// 2. Construct the MMS Message Payload
const mmsPayload = new MMSImage({
to: recipientNumber, // Recipient's phone number (E.164 format recommended)
from: process.env.VONAGE_MMS_SENDER_NUMBER, // Your Vonage US MMS number from .env
image: {
url: imageUrl, // Publicly accessible URL of the image
caption: caption || 'Image message', // Optional caption
},
// Optional: client_ref for tracking messages on your side
// client_ref: `my-internal-id-${Date.now()}`
});
// 3. Send the MMS using Vonage SDK
try {
console.log(`Attempting to send MMS to ${recipientNumber} from ${process.env.VONAGE_MMS_SENDER_NUMBER}`);
const response = await vonageMessages.send(mmsPayload);
console.log('Vonage API Response:', response);
// Check response for success indication (structure might vary slightly)
if (response.message_uuid) {
console.log(`MMS submitted successfully! Message UUID: ${response.message_uuid}`);
return res.status(200).json({
success: true,
message: 'MMS submitted successfully',
message_uuid: response.message_uuid,
});
} else {
// Handle cases where Vonage might return 2xx but without a message_uuid (unlikely for success)
console.error('MMS submission failed or response format unexpected:', response);
return res.status(500).json({
success: false,
message: 'MMS submission failed or Vonage response format unexpected.',
details: response // Include Vonage response for debugging
});
}
} catch (error) {
console.error('Error sending MMS via Vonage:', error);
// Provide more specific feedback based on potential Vonage errors
let statusCode = 500;
let errorMessage = 'Failed to send MMS due to an internal server error.';
// Check if the error object has Vonage-specific structure
if (error.response && error.response.data) {
console.error('Vonage Error Details:', error.response.data);
errorMessage = `Vonage API Error: ${error.response.data.title || error.message}`;
// Use status from Vonage response if available, otherwise keep 500
statusCode = typeof error.response.status === 'number' ? error.response.status : 500;
} else if (error.request) {
// The request was made but no response was received
errorMessage = 'Failed to send MMS: No response received from Vonage API.';
} else {
// Something happened in setting up the request that triggered an Error
errorMessage = `Failed to send MMS: ${error.message}`;
}
return res.status(statusCode).json({
success: false,
message: errorMessage,
// Safely access potential error details
errorDetails: error.response?.data
});
}
});
// --- Basic Root Route (Optional) ---
app.get('/', (req, res) => {
res.send('Vonage MMS Sender API is running!');
});
// --- Webhook Endpoints (Placeholder - Must return 200 OK) ---
// These are required by the Vonage Application configuration but are not
// fully implemented in this sending-focused guide.
// In production, you'd process status updates and inbound messages here.
app.post('/webhooks/status', (req, res) => {
console.log('Received Status Webhook:', req.body);
res.status(200).end(); // Always respond with 200 OK quickly
});
app.post('/webhooks/inbound', (req, res) => {
console.log('Received Inbound Webhook:', req.body);
res.status(200).end(); // Always respond with 200 OK quickly
});
// --- Start Server ---
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
console.log(`MMS sending endpoint available at http://localhost:${PORT}/send-mms`);
if (process.env.NODE_ENV !== 'production') {
console.log('Ensure ngrok is running and forwarding to this port if testing webhooks locally.');
}
});Code Explanation:
- Dependencies & Setup: Imports necessary modules (
express,@vonage/messages,dotenv). Loads environment variables usingdotenv.config(). - Vonage Client Initialization:
- Performs essential validation to ensure all required environment variables are set. Exits if any are missing.
- Creates an instance of the
Messagesclient using credentials fromprocess.envwithin atry...catchblock to handle potential initialization errors (e.g., bad key path).
- Express Setup: Initializes the Express app and adds middleware to parse JSON and URL-encoded request bodies.
/send-mmsEndpoint (POST):- Defines an asynchronous route handler for
POST /send-mms. - Input Validation: Retrieves
recipientNumber,imageUrl, andcaptionfrom the request body (req.body). Performs basic checks to ensure required fields are present and formats are plausible (digit-based number, valid URL). Returns a400 Bad Requestif validation fails. - Payload Creation: Creates an
MMSImageobject. This is the specific payload type for sending image MMS via the Messages API. It requires:to: The recipient's phone number. E.164 format (e.g.,+12125551234) is recommended for international compatibility, but Vonage often handles US numbers without the+.from: Your Vonage US MMS number from the.envfile.image: An object containing:url: A publicly accessible URL pointing directly to the image file (.jpg, .png, .gif supported). Vonage needs to fetch the image from this URL.caption: Optional text to accompany the image.
- Sending MMS: Calls
vonageMessages.send(mmsPayload)within atry...catchblock. This method returns a promise that resolves with the API response or rejects with an error. - Response Handling:
- If the
sendcall is successful and returns amessage_uuid, it logs success and sends a200 OKresponse back to the client including the UUID. - If the call fails (throws an error), the
catchblock executes.
- If the
- Defines an asynchronous route handler for
- Error Handling:
- The
catchblock logs the detailed error. - It attempts to extract useful information from the Vonage error response (if available) like the status code and error message (
error.response.data). - Sends an appropriate HTTP status code (e.g., 500, or the status from Vonage) and a JSON error message back to the client.
- The
- Webhook Placeholders: Includes basic handlers for
/webhooks/statusand/webhooks/inbound. These simply log the incoming webhook data and immediately return200 OK. This is crucial because Vonage expects a quick success response for webhooks. In a real application, you would add logic here to process delivery statuses or handle incoming messages. - Server Start: Starts the Express server, listening on the port specified in
.env(or 3000). Logs messages indicating the server is running and the endpoint is available.
5. Testing the MMS API
You can test the /send-mms endpoint using tools like curl or Postman.
-
Start the Server: Open your terminal in the project directory and run:
bashnode index.jsYou should see output indicating the server is listening on port 3000.
-
Test with
curl: Open a new terminal window. Replace placeholders with a valid recipient number (remember trial account restrictions) and a publicly accessible image URL.bashcurl -X POST http://localhost:3000/send-mms \ -H 'Content-Type: application/json' \ -d '{ "recipientNumber": "RECIPIENT_PHONE_NUMBER", "imageUrl": "https://placekitten.com/g/200/300", "caption": "Hello from Vonage MMS!" }'- Replace
RECIPIENT_PHONE_NUMBERwith the target phone number (e.g.,15551234567). If using a trial Vonage account, this number must be added to your allowed list in the Vonage Dashboard (under your profile/settings). - You can use the
placekitten.comURL for testing or any other direct link to a public image.
- Replace
-
Expected Output (
curl): If successful, you should receive a JSON response like this:json{ "success": true, "message": "MMS submitted successfully", "message_uuid": "some-unique-message-identifier" } -
Check Server Logs: Look at the terminal where
node index.jsis running. You should see logs indicating the request was received and the Vonage API response. -
Check Recipient Phone: The recipient number should receive the MMS message with the image and caption shortly. Delivery times can vary.
-
Testing Errors:
- Invalid Input: Send a request missing
recipientNumberorimageUrl. You should get a400 Bad Requestresponse. - Invalid Credentials: Temporarily modify your
.envfile with incorrect API keys and restart the server. Send a request; you should get an authentication error (likely 401). - Non-Whitelisted Number (Trial Account): If using a trial account, send to a number not on your whitelist. You should receive an error indicating the destination is not allowed.
- Invalid Input: Send a request missing
6. Troubleshooting and Common Issues
- Trial Account Limitations: Vonage trial accounts can only send messages to phone numbers you have verified and added to your "Allowed Numbers" or "Test Numbers" list in the dashboard settings. Add your test recipient number there.
- A2P (Application-to-Person) Only: The Vonage Messages API (and MMS in general via this method) is intended for Application-to-Person traffic. You generally cannot send MMS from one Vonage virtual number to another virtual number. The recipient must be a real mobile subscriber number.
- US/Canadian Sending Focus: Vonage MMS sending via the Messages API is primarily supported from US 10DLC, Toll-Free, or Short Code numbers to recipients within the US and Canada. International MMS support is limited and may vary. Check Vonage documentation for specifics.
- Image File Size and Format Requirements (Critical for Delivery):
- Recommended File Size: Keep images under 500 KB for reliable delivery across all carriers. Most US/Canadian carriers support up to 1 MB, but smaller files ensure faster delivery and broader compatibility.
- Time-Sensitive Messages: Limit file size to 150 KB or less for critical, time-sensitive campaigns to maximize delivery speed.
- Format Selection: Use PNG for best quality (lossless compression) or JPEG for smaller file sizes. GIF is supported for animated content.
- Optimal Dimensions: Target 9:16 aspect ratio (portrait orientation) with dimensions of 1080×1920 px or 640×1138 px for optimal mobile viewing.
- Carrier Rejection Risk: If your image exceeds the recipient's carrier limit, the carrier may reject or heavily compress the file, resulting in poor quality or failed delivery.
- Publicly Accessible Image URL: The
imageUrlmust point directly to the image file and be accessible from the public internet without requiring logins, authentication, or special headers. Vonage servers need to fetch this image. Test the URL in an incognito browser window to verify public accessibility. HTTPS URLs are recommended for security. - Correct SDK (
@vonage/messages): Ensure you are using@vonage/messages(v1.20.3 or later as of January 2025) and initializing it correctly, not the older@vonage/server-sdk'svonage.message.sendSmsor similar methods, which do not support MMS via the Messages API standard flow. - Webhook URLs Must Be Public & Respond 200 OK: Even if you aren't processing them yet, the Status and Inbound URLs configured in your Vonage Application must be reachable by Vonage and return a
200 OKquickly. ngrok handles the public accessibility during development. Your placeholder routes inindex.jshandle the200 OKresponse. Failure to respond correctly can lead to Vonage disabling webhooks for your application. - Private Key Path: Double-check the
VONAGE_PRIVATE_KEY_PATHin your.envfile exactly matches the location of yourprivate.keyfile relative to where you runnode index.js. The SDK expects a path to the file. - Application ID & Linked Number: Ensure you are using the correct Application ID and that your sending number is properly linked to that specific application in the Vonage dashboard.
- Default API Set to
Messages API: Re-verify the account-level setting mentioned in Step 2.3. Using the wrong default API (e.g., "SMS API") will cause incompatibility with the@vonage/messagesSDK and webhook formats. - Rate Limiting: Vonage applies rate limits to API calls (typically 30 requests/second per API key for Messages API as of January 2025). For high-volume applications, implement proper queuing and potentially request limit increases from Vonage. The basic Express app doesn't include rate limiting; consider libraries like
express-rate-limitfor production. - Error Handling: The provided error handling is basic. Production applications should use a dedicated logging library (like Winston or Pino) and integrate with error tracking services (like Sentry). Parse Vonage error codes for more specific retry logic if needed.
- Multi-Channel Failover (Q3 2025 Feature): Vonage introduced multi-channel failover capabilities in Q3 2025, enabling seamless transitions between RCS, SMS, and MMS. Consider implementing failover arrays in your message payload for improved delivery rates.
Frequently Asked Questions About Sending MMS with Node.js and Vonage
What is the maximum file size for MMS images with Vonage?
Keep images under 500 KB for reliable delivery across all US and Canadian carriers. While most carriers support up to 1 MB and some allow up to 2 MB, smaller files ensure faster delivery and broader compatibility. For time-sensitive campaigns, limit file size to 150 KB or less to maximize delivery speed.
What image formats does Vonage MMS support?
Vonage MMS supports three image formats: JPEG/JPG, PNG (recommended for lossless quality), and GIF (including animated GIFs). PNG is the preferred format as it maintains quality without compression artifacts, while JPEG works well for photographs where smaller file sizes are needed.
Can I send MMS to international numbers with Vonage?
Vonage MMS is primarily supported from US 10DLC, Toll-Free, or Short Code numbers to US and Canadian recipients. International MMS support is limited and varies by destination country. For international messaging, consider using WhatsApp or other channels supported by the Vonage Messages API's multi-channel capabilities.
Why is my MMS not delivering to the recipient?
Common delivery issues include: (1) Image file exceeds carrier limits (keep under 500 KB), (2) Image URL is not publicly accessible (test in incognito browser), (3) Trial account restriction (recipient must be on allowed list), (4) Wrong number format (use E.164 format like +12125551234), (5) Default SMS API not set to "Messages API" in Vonage dashboard settings.
What Node.js version do I need for Vonage MMS?
Use Node.js v22.x LTS (recommended as of January 2025) or v20.x (maintenance mode). Node.js v18.x reached end-of-life on April 30, 2025 and is no longer supported. The @vonage/messages SDK (v1.20.3 as of January 2025) requires a modern Node.js version for optimal performance.
How do I test MMS sending without using real phone numbers?
For development testing: (1) Use your own phone number added to the Vonage trial account allowed list, (2) Purchase a test Vonage number to receive messages, (3) Use ngrok to test webhook delivery locally, (4) Check Vonage dashboard logs for submission status even if delivery fails. For production testing, implement a staging environment with dedicated test numbers.
What is the difference between @vonage/messages and @vonage/server-sdk?
@vonage/messages (v1.20.3 as of January 2025) is the correct SDK specifically for the Messages API, supporting MMS, SMS, WhatsApp, and other channels with modern features like multi-channel failover. @vonage/server-sdk is the older, consolidated SDK. For MMS via the Messages API, always use @vonage/messages.
How do I optimize MMS images for mobile devices?
Use a 9:16 aspect ratio (portrait orientation) with dimensions of 1080×1920 px or 640×1138 px for optimal mobile viewing. Choose PNG for quality or JPEG for smaller file sizes. Keep total file size under 500 KB. Test images on multiple devices before sending to production users.
Can I send video files via MMS with Vonage?
Yes, Vonage MMS supports MP4 or 3GP video formats and MP3 audio formats. However, video files must also stay within carrier file size limits (recommended maximum 500 KB). For larger video content, consider using link previews or WhatsApp messaging instead, which have higher file size limits.
How many MMS messages can I send per second with Vonage?
The Vonage Messages API has a default rate limit of 30 requests per second per API key (verified January 2025). This applies to all message types including MMS. For high-volume applications, implement proper queuing with libraries like BullMQ and contact Vonage support to potentially increase your rate limits.
What happens if my image URL requires authentication?
Vonage servers must fetch your image directly from the provided URL without authentication. If your image requires login credentials, API keys, or special headers, MMS delivery will fail. Host images on a publicly accessible CDN or storage service (like AWS S3 with public read permissions, Cloudinary, or Imgur). Use HTTPS URLs for security.
7. Production Deployment Considerations
- Environment Variables: In production environments (like Heroku, AWS, Docker containers), do not commit your
.envfile. Use the hosting provider's mechanism for setting environment variables securely. - Hosting Options: Deploy this Node.js application like any other:
- PaaS (Heroku, Vercel): Configure environment variables via their dashboards/CLI. Ensure your
Procfile(for Heroku) or build settings correctly start the server (node index.js). - Docker: Create a
Dockerfileto containerize the application, manage dependencies, and securely inject environment variables during container runtime. - VPS/Server: Use process managers like
pm2to run the Node.js application reliably in the background. Configure environment variables via system environment or.env(with appropriate file permissions).
- PaaS (Heroku, Vercel): Configure environment variables via their dashboards/CLI. Ensure your
- Webhooks in Production: Replace ngrok URLs in your Vonage Application settings with your production server's public URLs for the
/webhooks/statusand/webhooks/inboundendpoints. Ensure these endpoints are secured (e.g., via signature verification if needed, although basic200 OKis often sufficient for status/inbound if processing happens elsewhere). - CI/CD: Set up pipelines (e.g., GitHub Actions, GitLab CI, Jenkins) to automate testing, building (if using TypeScript or a build step), and deploying your application to staging/production environments upon code changes.
8. Verification Checklist and Next Steps
Verification Checklist:
- Vonage Account Created
- API Key & Secret obtained and stored in
.env - US MMS-Capable Number Purchased
- Default SMS API set to
Messages APIin Vonage Settings - Vonage Application Created
- Public/Private Key Pair Generated,
private.keysaved securely - Messages Capability Enabled in Application
- Webhook URLs (Status/Inbound) configured (using ngrok or production URL)
- Application ID obtained and stored in
.env - Vonage Number Linked to the Application
- Project initialized (
npm init) - Dependencies installed (
express,@vonage/messages,dotenv) .gitignoreconfigured correctly.envfile populated with all credentials and pathsindex.jscode implemented as shown- Server starts without errors (
node index.js) - Test request sent via
curlor Postman to/send-mms - Successful
200 OKresponse received from API withmessage_uuid - Server logs show successful submission
- MMS message (image + caption) received on the recipient's phone
Next Steps:
- Robust Error Handling: Implement more detailed parsing of Vonage error codes and potentially add retry logic for transient network issues.
- Logging: Integrate a production-grade logging library (Winston, Pino).
- Webhook Processing: Build out the logic in
/webhooks/statusto store or react to delivery receipts (e.g.,delivered,failed). Implement/webhooks/inboundif you need to receive MMS/SMS replies. - Security: Implement webhook signature verification (if required for your security posture), add rate limiting (
express-rate-limit), and sanitize all inputs thoroughly. - Input Validation: Use a dedicated validation library (like Joi or express-validator) for more complex validation rules.
- Database Integration: Store message UUIDs, statuses, and other relevant information in a database for tracking and reporting.
- Send Other Media: Explore sending video or other file types supported by MMS and the Vonage API.
- Frontend Integration: Build a user interface that interacts with this API.
- Multi-Channel Failover: Implement failover arrays to leverage Vonage's Q3 2025 multi-channel failover feature for improved delivery rates across RCS, SMS, and MMS.
- Image Optimization Pipeline: Add automated image resizing and compression to ensure all MMS images stay under 500 KB before sending.
- Monitoring and Alerts: Set up monitoring for delivery rates, error rates, and webhook processing to catch issues early.
Related Resources
- Vonage Messages API Documentation
- Vonage MMS Code Snippets
- MMS FAQ – Vonage Support
- @vonage/messages npm Package
- Node.js LTS Schedule
- How to Send SMS with Node.js
- Vonage 10DLC Registration Guide
- WhatsApp Business API with Node.js
You now have a functional Node.js Express application capable of sending MMS messages using the Vonage Messages API. Remember to handle credentials securely and consult the Vonage Messages API documentation for more advanced features and details.
Verified as of January 2025. Technical specifications including Node.js versions (v22.x LTS recommended, v20.x maintenance mode, v18.x EOL April 30, 2025), SDK version (@vonage/messages v1.20.3), MMS file size limits (500 KB recommended, up to 1 MB supported by most US/Canadian carriers, 150 KB for time-sensitive campaigns), supported formats (JPEG, PNG recommended, GIF), optimal dimensions (9:16 aspect ratio, 1080×1920 px or 640×1138 px), rate limits (30 requests/second per API key), supported number types (US 10DLC, Toll-Free, Short Code), and multi-channel failover capabilities (Q3 2025) were verified against official Vonage documentation. MMS sending is primarily supported from US numbers to US/Canadian recipients. API specifications and carrier requirements may change – check official Vonage documentation for the most current information.