Frequently Asked Questions
Use the Vonage Messages API with the @vonage/server-sdk
and Express. Create a POST endpoint that takes the recipient number, your Vonage number, an image URL, and an optional caption. The endpoint then uses the Vonage SDK to send the MMS message.
The Vonage Messages API is a unified interface for sending various types of messages including SMS, MMS, WhatsApp, Viber, and Facebook Messenger. It simplifies the process of integrating messaging into applications using a single API.
Vonage currently restricts MMS sending via its API to US-based virtual numbers (10DLC, Toll-Free, Short Codes) due to regulatory and carrier requirements for Application-to-Person (A2P) messaging in the US.
ngrok is essential during development to expose your local server's webhook endpoint to the public internet. This lets Vonage deliver status updates to your app even when it's running locally.
The guide focuses on MMS within the US from US Vonage numbers to US destinations. For information on other countries or message types, refer to the full Vonage Messages API documentation.
Obtain your Application ID and Private Key from the Vonage dashboard when creating a Vonage Application. Store these securely in a .env
file. You also need a US virtual number linked to your Vonage application.
The status webhook URL, configured in your Vonage Application, provides delivery status updates (DLRs) such as 'delivered', 'failed', or 'rejected' for each MMS message sent. This helps track message delivery outcomes.
Implement try...catch
blocks around API calls and validate input parameters to catch errors early. Log errors comprehensively using libraries like pino
or winston
. Consider retry mechanisms with exponential backoff for temporary errors, but avoid retrying client errors.
The dotenv
package loads environment variables from a .env
file into process.env
, allowing you to manage configuration separately from your code, especially for sensitive credentials like API keys and private keys.
Initialize a project with npm init
, install dependencies (express
, @vonage/server-sdk
, dotenv
), create index.js
for main logic, .env
for configuration, and .gitignore
to exclude sensitive files from version control.
Storing message data enables tracking of sent messages, delivery statuses, errors, and other relevant information. This supports reporting, debugging, and potential compliance requirements.
Express.js simplifies building the API endpoint to handle incoming MMS send requests. It manages routing, request parsing, and sending responses, making the interaction with Vonage straightforward.
Send MMS Messages with Vonage, Node.js & Express
Build a production-ready Node.js application using the Express framework to send Multimedia Messaging Service (MMS) messages via the Vonage Messages API.
Learn everything from initial project setup and Vonage configuration to implementing the core sending logic, handling errors, securing credentials, and preparing for deployment. This tutorial covers all essential aspects of programmatic MMS sending, including A2P 10DLC registration requirements, file size optimization, and webhook handling for delivery tracking.
Project Overview and Goals
What You're Building:
A simple Node.js web server using Express that exposes an API endpoint. When this endpoint receives a request containing a recipient phone number, a sender number (your Vonage number), an image URL, and an optional caption, it uses the Vonage Messages API to send an MMS message.
Problem Solved:
This guide enables you to programmatically send rich media content (images) directly to users' mobile devices within the US, enhancing communication beyond simple text messages. Use this for sending product images, event flyers, visual alerts, or personalized media. Common applications include e-commerce order confirmations with product images, appointment reminders with QR codes, real estate listings with property photos, and marketing campaigns with promotional graphics.
Technologies Used:
@vonage/server-sdk
: The official Vonage Server SDK for Node.js, simplifying interaction with Vonage APIs.dotenv
: A module to load environment variables from a.env
file intoprocess.env
, keeping sensitive credentials out of source code.ngrok
(for development): A tool to expose your local development server to the internet, necessary for receiving webhook callbacks from Vonage (like message status updates).Critical MMS Technical Specifications:
System Architecture:
A simplified view of the interaction:
Prerequisites:
Numbers
>Buy Numbers
). Note: MMS via Vonage is currently restricted to sending from US numbers (10DLC, Toll-Free, Short Code) to US destinations for Application-to-Person (A2P) use cases.ngrok
(Recommended for Development): For exposing your local server to receive status webhooks. (Download ngrok)Final Outcome:
By the end of this guide, you will have a functional Express application capable of sending MMS messages via a secure API endpoint, complete with basic error handling and configuration management using environment variables.
1. Setting up the Node.js Project
Initialize your Node.js project 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.
Initialize Node.js Project: Use
npm
to create apackage.json
file. The-y
flag accepts the default settings.Install Dependencies: Install Express, the Vonage Server SDK, and
dotenv
.express
: Web framework.@vonage/server-sdk
: Vonage API client library.dotenv
: Loads environment variables from a.env
file.Enable ES Modules (Optional but Recommended): To use modern
import
/export
syntax, open yourpackage.json
file and add the following line at the top level:(Adjust version numbers based on what
npm install
added). If you prefer CommonJS (require
), omit the"type": "module"
line and userequire
syntax throughout the code. This guide uses ES Modules syntax.Create Project Files: Create the main application file and the environment file.
Configure
.gitignore
: Addnode_modules
and your.env
file to.gitignore
to prevent committing them to version control. This is crucial for security.Project Structure: Your basic structure should now look like this:
This foundational setup provides a clean structure and installs the necessary tools for building your MMS sending application.
Note on SDK Version Compatibility: The current version of the Vonage Server SDK is v3.24.1 as of January 2025. This guide is designed to work with this version. If you encounter issues, ensure you are using the compatible SDK version. Check the SDK version in your
package.json
file or by runningnpm list @vonage/server-sdk
in your project directory. To update the SDK, usenpm update @vonage/server-sdk
to get the latest compatible version. For more information on SDK compatibility and updates, refer to the Vonage Server SDK documentation.2. Implementing Core Functionality (Sending MMS)
Write the core logic to interact with the Vonage SDK and send an MMS message. We'll encapsulate this in a reusable function.
Import Dependencies and Load Environment Variables: Open
index.js
and add the necessary imports. We usedotenv/config
to load variables immediately.Explanation:
dotenv/config
to load environment variables immediately.Vonage
client using theapplicationId
andprivateKey
path obtained from environment variables.path.resolve
ensures the path works correctly regardless of where you run the script from.messages
client specifically (vonage.messages
).sendMmsMessage
function takesto
,from
,imageUrl
, and an optionalcaption
.messagesClient.send()
with the specific structure required for MMS:message_type: 'image'
channel: 'mms'
image: { url: ..., caption: ... }
async/await
for cleaner asynchronous code.try...catch
block handles potential errors during the API call, logging details and re-throwing the error.This core function encapsulates the interaction with Vonage for sending MMS, making it easy to integrate into your API layer.
3. Building the API Layer with Express
Create an Express server and define an API endpoint to trigger your
sendMmsMessage
function.Set up Express Server: Add the following code to
index.js
, replacing the placeholder comments.Explanation:
express
and create an app instance.PORT
using an environment variable or defaulting to 3000.express.json
,express.urlencoded
) to parse incoming request bodies./health
endpoint for basic service monitoring./send-mms
endpoint is aPOST
route:to
,imageUrl
, andcaption
from thereq.body
.from
number directly from the environment variable.sendMmsMessage
function within atry...catch
block.202 Accepted
status (as sending is asynchronous) along with themessage_uuid
.500 Internal Server Error
response to the client./webhooks/status
endpoint to receive delivery status updates from Vonage. It logs the incoming payload and sends back a200 OK
immediately. This endpoint is crucial for tracking message delivery.app.listen
starts the server.Testing the API Endpoint:
npm start
ornpm run dev
.curl
or a tool like Postman to send a POST request:+14155550100
with a valid US test number (whitelisted if on trial).This API layer provides a structured way to interact with your MMS sending logic via HTTP requests.
4. Integrating with Vonage (Configuration & Credentials)
Proper configuration is key to connecting your application with Vonage.
Vonage API Account: Ensure you have a Vonage account.
Purchase/Verify MMS Number:
Numbers
>Buy numbers
.+12015550123
).Create a Vonage Application: The Messages API uses Applications and public/private key pairs for authentication when sending.
Applications
>Create a new application
.private.key
file that downloads. Store this securely and do not commit it to Git. A good practice is to place it outside your project directory or in a secure location referenced by your environment variables. For simplicity in this guide, you could place it in the project root, but ensure it's in.gitignore
.DLRs
). Use your/webhooks/status
endpoint. During local development, you needngrok
:ngrok http 3000
(assuming your server runs on port 3000).https
Forwarding URL provided by ngrok (e.g.,https://<unique-id>.ngrok.io
).<your-ngrok-url>/webhooks/status
into the "Status URL" field (e.g.,https://<unique-id>.ngrok.io/webhooks/status
). Set the method toPOST
.<your-ngrok-url>/webhooks/inbound
(or reuse status) and set method toPOST
.Configure Environment Variables (
.env
): Create or open the.env
file in your project root and add the following, replacing the placeholder values:VONAGE_APPLICATION_ID
: The ID generated when you created the Vonage application.VONAGE_PRIVATE_KEY_PATH
: The file path to theprivate.key
file you saved. Ensure this path is correct relative to where you runnode index.js
.VONAGE_MMS_NUMBER
: Your purchased US Vonage number capable of sending MMS, in E.164 format.PORT
: The port your Express server will listen on.TEST_RECIPIENT_NUMBER
: Only used if you uncomment the test block at the end of Section 2. Needs to be a number whitelisted on your Vonage trial account if applicable..env
file and theprivate.key
file contain sensitive credentials. Never commit them to version control. Use your.gitignore
file properly.Vonage Trial Account Restrictions: If your Vonage account is new and still in trial mode (you haven't added payment details and made a payment), you can typically only send messages to phone numbers you have verified and added to your Vonage dashboard's "test numbers" list. Navigate to your Dashboard > Account > Settings > Test Numbers to add and verify them.
Webhook Security (Important for Production): In production, verify that webhook requests actually come from Vonage by validating the signature. Vonage signs webhook requests using your application's signature secret. Implement signature verification in your webhook handler to prevent malicious requests. Refer to the Vonage webhook signature verification documentation for implementation details.
With these steps, your application is configured to authenticate with Vonage using your application credentials and send messages from your designated Vonage number. The status webhook configuration enables you to receive feedback on message delivery.
5. Implementing Error Handling, Logging, and Retry Mechanisms
Robust applications need proper error handling and logging.
Error Handling (Improved):
sendMmsMessage
function catches errors from the Vonage SDK. The SDK might throw errors for various reasons (invalid credentials, network issues, invalid parameters, API errors from Vonage). The error object often contains valuable details inerr.response.data
orerr.message
./send-mms
endpoint handles errors fromsendMmsMessage
and validation errors. It correctly logs detailed errors internally while returning user-friendly messages (e.g., 500 Internal Server Error) to the client, preventing potential information leakage.200 OK
quickly to Vonage to prevent unnecessary retries from their side. Handle processing asynchronously if it's complex.Logging:
console.log
andconsole.error
statements. This is sufficient for development but not ideal for production.winston
orpino
. These offer:pino
integration):Retry Mechanisms:
async-retry
can help.client_ref
parameter if supported for tracking. Retrying on validation errors (4xx) is generally pointless.Choose logging and retry strategies appropriate for your application's scale and reliability requirements. Start simple and enhance as needed.
6. Creating a Database Schema and Data Layer (Optional)
While not strictly required for just sending MMS, storing message information is common in real-world applications for tracking, reporting, and debugging.
Why Store Data?
Potential Schema (Conceptual – e.g., PostgreSQL with Prisma):
Implementation Steps (If Adding Database):
/send-mms
) to create a record in the database before or after callingsendMmsMessage
. Store themessage_uuid
returned by Vonage./webhooks/status
) to find the corresponding message record usingmessage_uuid
and update itsstatus
,lastUpdatedAt
, and potentiallyerrorCode
/errorReason
.Frequently Asked Questions (FAQ)
What is the maximum MMS file size I can send with Vonage?
While some carriers accept up to 3.5 MB, all US carriers reliably handle up to 300 KB. For optimal delivery rates and to avoid carrier compression or rejection, keep images under 500–600 KB. Files over 600 KB may be compressed by carriers or fail delivery on certain devices.
Which image formats are supported for MMS messaging?
JPEG (.jpg, .jpeg), PNG (.png), and GIF (.gif) are universally supported formats that ensure maximum compatibility across all US carriers and devices. While other formats may be accepted, these three formats guarantee successful delivery.
Can I send MMS internationally with Vonage?
No, Vonage MMS is currently limited to sending from US numbers (10DLC, Toll-Free, or Short Code) to US destinations only for Application-to-Person (A2P) messaging. International MMS is not available via Vonage Messages API as of January 2025.
What is A2P 10DLC registration and do I need it for MMS?
A2P 10DLC (Application-to-Person 10-Digit Long Code) registration is mandatory for all business messaging in the US, including MMS. Register your brand and campaign with Vonage before sending to US numbers. Unregistered numbers face severe filtering and blocking by carriers. Registration typically takes 1–2 weeks and costs vary by throughput tier.
How do I handle MMS delivery status updates?
Configure a webhook endpoint in your Vonage application settings to receive delivery receipts (DLRs). Vonage will POST status updates (submitted, delivered, failed, rejected) to your webhook URL. Your endpoint must respond with HTTP 200 OK quickly to acknowledge receipt.
Why must my image URL be publicly accessible HTTPS?
Vonage servers need to fetch the image from your URL to send it via MMS. The URL must be publicly accessible via HTTPS (HTTP not supported), without authentication or CORS restrictions. Common hosting solutions include AWS S3 (public bucket), Cloudinary, Imgur, or CDN services.
What happens if my MMS message fails to deliver?
Vonage will attempt delivery and send a status webhook with failure details. Common reasons include invalid recipient numbers, carrier rejections, file size limits exceeded, unsupported formats, or unregistered 10DLC numbers. Check the error code and reason in the webhook payload for specific details.
How do I test MMS sending on a Vonage trial account?
Trial accounts can only send to verified test numbers. Add and verify test numbers in your Vonage Dashboard under Account > Settings > Test Numbers. Once verified, you can send MMS to these numbers for testing. Upgrade your account to send to any US number.
What are SHAFT content restrictions for MMS?
SHAFT content (Sex, Hate, Alcohol, Firearms, Tobacco) is strictly prohibited on all US number types for A2P messaging. Violations result in immediate account suspension. Ensure your MMS content complies with carrier guidelines and CTIA messaging principles.
Can I send MMS with captions using Vonage?
Yes, the Vonage Messages API supports optional captions for MMS images. Include the
caption
parameter in your API request. The caption appears as text alongside the image in the recipient's messaging app.How long does it take for an MMS to be delivered?
MMS delivery is typically near-instantaneous (within seconds) but can vary based on carrier processing, network conditions, and recipient device status. Monitor delivery status via webhooks to track actual delivery times for each message.
What version of the Vonage Node.js SDK should I use?
This guide uses @vonage/server-sdk v3.24.1 (latest as of January 2025). Version 3.x provides Promise-based APIs, TypeScript support, and improved error handling. Use
npm install @vonage/server-sdk
to install the latest compatible version.How do I deploy this application to production?
For production deployment:
Related Resources