Frequently Asked Questions
Use the Plivo Node.js SDK and Express.js to create an API endpoint. This endpoint receives recipient details and media URLs, then uses the Plivo API to send the MMS message. The project requires setting up a Node.js project and installing necessary dependencies like Express.js, Plivo's Node.js SDK, and dotenv.
The Plivo Node.js SDK simplifies interaction with the Plivo API. It provides convenient functions for sending SMS and MMS messages, making calls, and other Plivo functionalities, directly within your Node.js application. It handles the low-level API communication details, making your code cleaner and easier to manage. It's crucial for sending MMS messages as described in the guide.
MMS supports multimedia content like images, GIFs, videos, and audio, along with text. This makes MMS more engaging and versatile compared to SMS, which is limited to text-only messages. MMS enables richer communication, making it suitable for various applications like sharing product demos or sending personalized greetings.
Consider MMS when you need to send more than just text. If your message involves visuals, audio, or short videos, MMS is the preferred choice. For example, send order confirmations with product images or promotional messages with engaging GIFs using MMS instead of plain text SMS.
Yes, a free trial Plivo account is sufficient to test MMS functionality. However, remember you can only send test MMS messages to numbers verified within your Plivo sandbox environment during the trial period. This important step avoids common delivery issues when starting.
After signing up for a Plivo account, locate your Auth ID and Auth Token on the Plivo console dashboard. Store these securely in a .env
file in your project root directory, and never commit this .env
file to version control. The dotenv package will load these values into process.env at runtime.
Express-validator is used for request data validation. It ensures that incoming data to your API endpoint meets specific criteria, like required fields and data types, enhancing security and preventing errors caused by bad input. This adds a layer of protection and ensures data integrity.
Within the Plivo console, navigate to 'Messaging' > 'Sandbox Numbers'. Add the phone numbers you will use as recipients during testing and follow the steps to verify them. This verification is mandatory for sending MMS messages with a trial account.
Use dedicated secret management services such as AWS Secrets Manager, Google Secret Manager, Azure Key Vault, or tools like HashiCorp Vault. Avoid storing credentials in .env
files for production deployments, as these present security risks.
Implement unit tests for the plivoService.js
file. Mock the Plivo client object using Jest's mocking capabilities, which allows testing your service's logic and interaction with the Plivo SDK without making real API calls or incurring costs.
Central error handling middleware catches errors passed using next(error)
and provides a consistent way to handle unexpected issues. It logs errors, sets an appropriate HTTP status code (like 500 Internal Server Error), and sends a standardized error response to the client, preventing information leakage and simplifying debugging.
Implement rate limiting to prevent abuse, enforce HTTPS using a reverse proxy with TLS/SSL certificates, add strong input validation, and secure sensitive configuration like API keys with dedicated secret management services. These measures are crucial for a production-ready application.
Implement rate limiting using a library like express-rate-limit
. This middleware limits the number of requests from a particular IP address within a timeframe, preventing accidental or malicious overuse of the Plivo API which can lead to unexpected charges.
Use environment variables and tools like dotenv for local development. For production, use dedicated secret management solutions for sensitive configuration and consider more robust error handling and logging practices. Always avoid exposing sensitive data directly in your code.
Multimedia Messaging Service (MMS) transforms user communication by enabling you to send MMS messages with images, GIFs, videos, and audio alongside text. While standard SMS delivers text only, multimedia messaging creates engaging experiences that capture attention and drive action. MMS messages achieve 3–5× higher engagement rates than SMS, with click-through rates averaging 15–20% compared to 3–5% for text-only messages.
When to use MMS vs. SMS:
This guide shows you how to build production-ready Node.js MMS applications using the Plivo API. Master Plivo MMS integration with Express.js by creating secure API endpoints, implementing validation, handling errors gracefully, and deploying with confidence. Build a simple API endpoint that accepts recipient details and media information, then reliably sends MMS via Plivo.
Project Goals:
Technologies Used:
Prerequisites:
System Architecture:
This guide walks you through creating the "Node.js / Express API" component.
1. Setting Up the Project
Initialize your Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal and create a new directory for your project, then navigate into it.
Initialize Node.js Project: This creates a
package.json
file to manage dependencies and project information.Install Dependencies: Install
express
for the web server,plivo
for the SDK,dotenv
for environment variables, andexpress-validator
for input validation.express
: The web framework.plivo
: The official Plivo SDK.dotenv
: Loads environment variables from a.env
file intoprocess.env
. Essential for keeping secrets out of code.express-validator
: Provides middleware for validating incoming request data, crucial for security and data integrity.Set Up Project Structure: Create the following basic structure within your
node-plivo-mms
directory:src/
: Contains the main application code.controllers/
: Handles incoming requests, validates data, and calls services.middleware/
: Contains custom middleware, like validators.routes/
: Defines API endpoints and maps them to controllers.services/
: Contains business logic, including interaction with external APIs like Plivo.app.js
: Sets up the Express application, middleware, and starts the server..env
: Stores sensitive configuration like API keys..gitignore
: Prevents sensitive files (like.env
) and unnecessary files (likenode_modules
) from being committed to version control.Create
.gitignore
: Create a file named.gitignore
in the project root and add the following:Set Up Environment Variables (
.env
): Create a file named.env
in the project root. This file holds your Plivo credentials and configuration. Never commit this file to Git.PLIVO_AUTH_ID
,PLIVO_AUTH_TOKEN
: Your Plivo API credentials.PLIVO_SOURCE_NUMBER
: The Plivo phone number in E.164 format (e.g.,+14155551212
) that sends the MMS. It must be MMS-enabled. E.164 is the international telephone numbering standard that requires a+
prefix, country code (1–3 digits), and subscriber number (up to 12 digits), with no spaces or special characters.PORT
: The port on which your Node.js application listens.2. Plivo Account Setup for MMS
Before writing code, ensure your Plivo account is ready.
Sign Up/Log In: Go to Plivo.com and sign up for an account or log in.
Find Auth ID and Auth Token:
Auth ID
andAuth Token
are prominently displayed on the overview dashboard page..env
file forPLIVO_AUTH_ID
andPLIVO_AUTH_TOKEN
.Get an MMS-Enabled Phone Number:
+
and country code) and paste it into your.env
file forPLIVO_SOURCE_NUMBER
.Trial Account Limitation (Sandbox Numbers):
3. Implement Plivo MMS API Service in Node.js
Encapsulate the Plivo interaction within a dedicated service file.
Create
src/services/plivoService.js
:Use
media_urls
vs.media_ids
:media_urls
: Reference externally hosted files (AWS S3, Cloudinary, etc.). Plivo fetches the media at send time. Use this for dynamic content or when you manage your own media storage.media_ids
: Reference files uploaded to Plivo's media library via console or API. Use this for frequently reused assets (logos, brand images) to reduce latency and avoid external URL failures.Plivo API response structure:
message_uuid
: Array of unique IDs for tracking delivery status.api_id
: Request identifier for Plivo support inquiries.Common Plivo error codes:
Explanation:
plivo
and load environment variables usingdotenv.config()
.Client
is initialized. It capturesPLIVO_AUTH_ID
andPLIVO_AUTH_TOKEN
at load time.sendMms
function takes the destination number, text, and media URL as arguments.sourceNumber
,PLIVO_AUTH_ID
,PLIVO_AUTH_TOKEN
) are performed inside the function to make testing environment variable changes easier.client.messages.create
is the core Plivo SDK method.src
: Your Plivo MMS number (PLIVO_SOURCE_NUMBER
).dst
: The recipient's number.text
: The message body.type: 'mms'
and provide themedia_urls
as an array. Plivo fetches the media from this URL and attaches it.media_urls
must be publicly accessible.async/await
for cleaner asynchronous code.console.log
andconsole.error
are used here for simplicity. In production, replace these with a robust logging library like Winston or Pino (discussed further in Deployment section).4. Building the API Layer (Routes and Controller)
Create the Express route and controller to expose MMS sending functionality via an API endpoint.
1. Create Route (
src/routes/mmsRoutes.js
):Explanation:
POST
route at/send
. The full path is/api/mms/send
when mounted inapp.js
.validateSendMms
middleware to validate the request body beforemmsController.sendMmsHandler
executes.2. Create Controller (
src/controllers/mmsController.js
):Explanation:
validationResult
function fromexpress-validator
and theplivoService
.sendMmsHandler
function first checks ifvalidationResult(req)
found any errors defined by validator middleware. If so, it immediately sends a400 Bad Request
response.destinationNumber
,text
, andmediaUrl
from the request body (req.body
).plivoService.sendMms
within atry...catch
block.200 OK
response including Plivo API's confirmation.plivoService.sendMms
throws an error (either configuration error or Plivo API error), thecatch
block catches it and passes it to Express's error handling mechanism usingnext(error)
.5. Implementing Input Validation
Validate input to ensure security and prevent errors. Use
express-validator
.Create the directory
src/middleware
and inside it, createvalidators.js
:Explanation:
body
function fromexpress-validator
to define validation rules for fields expected in the request body.destinationNumber
: Check it's not empty, is a string, and roughly matches the E.164 format (starts with+
, followed by digits). For production, consider more robust phone number validation.text
: Check for non-emptiness and being a string.mediaUrl
: Check for non-emptiness and being a valid URL format usingisURL()
..trim()
removes leading/trailing whitespace..withMessage()
provides custom error messages.validateSendMms
array of middleware is exported and used insrc/routes/mmsRoutes.js
.6. Setting Up the Express App and Error Handling
Tie everything together in
src/app.js
.Explanation:
dotenv
first to ensure environment variables are available.express
app.express.json()
: Essential middleware to parse incoming JSON request bodies (like the one sent to/api/mms/send
).mmsRoutes
under the/api/mms
prefix. The actual endpoint isPOST /api/mms/send
./health
endpoint is added as a best practice for monitoring.next(error)
(like in the controller's catch block) is caught here.PORT
..env
.console.log
andconsole.warn
. Replace these with a dedicated logging library for production applications.7. Security Considerations
While this guide covers basics, production systems require more robust security.
PLIVO_AUTH_ID
andPLIVO_AUTH_TOKEN
are highly sensitive..env
and.gitignore
..env
files.express-validator
. Ensure your validation rules are strict and cover all expected inputs to prevent injection attacks or unexpected behavior.express-rate-limit
package is a popular choice.app.js
before your routes:/api/mms/send
endpoint so only authorized users or systems can trigger MMS sending (e.g., using API keys, JWT tokens, OAuth).cors
package to control which domains can access your API:app.js
:helmet
to set secure HTTP headers:app.js
:+1415555****
).8. Testing Your Plivo MMS Integration
Test to ensure your code works as expected and prevent regressions.
1. Unit Testing (Plivo Service): Unit test the service layer by mocking the Plivo client.
Install Jest:
Add a test script to
package.json
:Create a test file
src/services/plivoService.test.js
:Run tests:
npm test
Explanation of Test Changes:
jest.resetModules()
is added tobeforeEach
to ensure thatplivoService
(and its dependency onprocess.env
) is freshly loaded for each test, reflecting any changes made toprocess.env
.require
d inside each test case to ensure the test uses the environment variables set for that specific test scope.2. Integration Testing (API Endpoint): Test the full request-response cycle of your API endpoint.
Install Supertest:
Create a test file
src/routes/mmsRoutes.test.js
:Run tests:
npm test
Best practices for testing:
9. Running the Application
.env
is correct: Double-check yourPLIVO_AUTH_ID
,PLIVO_AUTH_TOKEN
, andPLIVO_SOURCE_NUMBER
in the.env
file.http://localhost:3000/api/mms/send
Content-Type: application/json
Monitoring MMS delivery status:
Debugging failed sends:
Frequently Asked Questions
How do I send MMS with Plivo in Node.js?
Install the Plivo SDK (
npm install plivo
), authenticate with your Auth ID and Token, then callclient.messages.create()
with thefrom
number (MMS-enabled),to
number,text
, andmedia_urls
array. Plivo delivers the MMS to the recipient's device via your verified phone number.What file formats does Plivo MMS support?
Plivo MMS supports images (JPEG, PNG, GIF), videos (MP4, 3GP), and audio (MP3, AMR). Maximum file size is 5MB per message. Host files on publicly accessible URLs (HTTPS recommended) and pass them in the
media_urls
array when sending. Some carriers restrict specific formats (e.g., AT&T may block certain animated GIFs), so test across carriers before production deployment.How much does it cost to send MMS with Plivo?
Plivo MMS pricing varies by destination country and carrier. US/Canada MMS typically costs $0.02–$0.04 per message. Check your Plivo dashboard pricing page for current rates. MMS costs more than SMS due to multimedia content delivery and increased carrier processing. Plivo doesn't charge separately for media storage or bandwidth – all costs are per-message.
Do I need a special Plivo phone number for MMS?
Yes, your Plivo phone number must be MMS-enabled. Not all Plivo numbers support MMS by default. Purchase MMS-capable numbers from your Plivo console or verify existing numbers have MMS capability. SMS-only numbers reject MMS requests with error responses.
How do I handle Plivo MMS delivery callbacks?
Configure a webhook URL in your Plivo console under Messaging settings. Plivo sends POST requests to this URL with delivery status updates. Parse the
Status
,MessageUUID
, andErrorCode
fields to track delivered, failed, or queued messages in your application.Example webhook implementation:
Can I send MMS to international numbers with Plivo?
Yes, but MMS availability varies by country and carrier. Many countries support MMS, but some regions have limited carrier support or higher costs. Verify international MMS support in Plivo's coverage documentation before implementing. Consider SMS fallback for unsupported destinations.
What is the maximum size for Plivo MMS messages?
Plivo enforces a 5MB limit per MMS message across all media files combined. If you include multiple images or videos, their total size cannot exceed 5MB. Compress or resize media files before sending to stay within limits and reduce delivery costs.
Best practices for media optimization:
How do I test Plivo MMS without sending real messages?
Use Plivo's trial account with verified phone numbers (add recipients in Sandbox Numbers). Test with small image URLs (under 500KB) to validate integration. Check Plivo's message logs in the console for delivery status. Use tools like Postman or curl to test your API endpoint locally before production deployment.
10. Production Deployment
Environment setup:
console.log
with Winston or Pino for structured logging..env.production
,.env.staging
).Monitoring and observability:
Scaling considerations:
Deployment checklist:
npm test
)Common production issues: