Frequently Asked Questions
You can send MMS messages by integrating Plivo's MMS API into your RedwoodJS application. This involves creating a Redwood service that uses the Plivo Node.js SDK and exposing this service via a GraphQL mutation. The service handles interaction with the Plivo API, sending media URLs and optional text to recipients.
Plivo is a cloud communications platform that enables sending MMS, SMS, and voice messages. In a RedwoodJS application, the Plivo Node.js SDK is used within a service to interact with the Plivo API for sending multimedia messages, including images and GIFs.
Plivo provides a convenient API and Node.js SDK for integrating MMS functionality into a RedwoodJS backend. It allows for richer communication, handling media that standard SMS cannot, and offers robust features for managing MMS campaigns.
Use a Plivo MMS service when you need to send messages containing rich media like images, GIFs, or other files directly from your RedwoodJS application. This is ideal for user engagement, notifications, or marketing campaigns in the US and Canada.
Plivo's MMS sending, as implemented in this RedwoodJS guide, is currently limited to US and Canadian numbers. Attempts to send to other regions will fail, so your application logic should handle these limitations.
First, install the Plivo Node.js SDK using `yarn workspace api add plivo`. Then, configure environment variables (`PLIVO_AUTH_ID`, `PLIVO_AUTH_TOKEN`, `PLIVO_SENDER_ID`) in a `.env` file. These credentials are essential for accessing the Plivo API and setting the appropriate sender number.
The `PLIVO_SENDER_ID` environment variable stores your MMS-enabled Plivo phone number in E.164 format (e.g., +14155551234). This is the number that will appear as the sender of the MMS messages.
You can find your Plivo Auth ID and Auth Token on the main dashboard overview page after logging in to your Plivo Console at https://console.plivo.com/.
The provided `sendMms` service includes error handling for missing environment variables, invalid input formats, and Plivo API errors. It returns a structured response, including a success flag, message, and error details for easier debugging and client feedback.
The `mediaUrl` provided to the Plivo API must be a publicly accessible URL. Plivo's servers need to download the media from this URL to attach it to the MMS message. Private or localhost URLs will not work.
During deployment to your chosen provider, add the `PLIVO_AUTH_ID`, `PLIVO_AUTH_TOKEN`, and `PLIVO_SENDER_ID` environment variables in the hosting platform's settings. Never commit your .env file containing these secrets.
Use the Redwood CLI command `yarn rw g service plivoMms` to generate the necessary service files. Then, implement the `sendMms` function in `api/src/services/plivoMms/plivoMms.ts`, using the provided code example, to handle MMS sending logic.
Install the Plivo SDK specifically into the `api` workspace using the command `yarn workspace api add plivo`. This ensures the package is only added as a dependency for the backend where it's required.
Define the GraphQL mutation in a new file named `api/src/graphql/plivoMms.sdl.ts`. The schema should include input arguments for the recipient number (`to`), media URL (`mediaUrl`), optional text (`text`), and a response type indicating success or failure.
This guide provides a step-by-step walkthrough for integrating Plivo's MMS API into your RedwoodJS application. We'll build a simple service and GraphQL mutation to send MMS messages, covering setup, implementation, error handling, and deployment best practices.
By the end of this tutorial, you'll have a functional RedwoodJS backend capable of sending MMS messages, including images or other media, via Plivo to recipients in the US and Canada. This enables richer communication for user engagement, notifications, or marketing campaigns directly from your application.
Last Updated: October 26, 2023
Project Overview and Goals
Goal: To implement a feature within a RedwoodJS application that allows sending Multimedia Messaging Service (MMS) messages using the Plivo communications platform.
Problem Solved: This addresses the need to send messages containing media (images, GIFs, etc.) in addition to text, which standard SMS cannot handle effectively. It provides a programmatic way to enhance user communication directly from the application backend.
Technologies Used:
System Architecture:
plivoMms.ts
).plivoMms
service uses the Plivo Node.js SDK, configured with API credentials and sender details, to make an API request to Plivo.Prerequisites:
yarn global add redwoodjs
)1. Setting up the Project
We'll start with a fresh RedwoodJS project. If you have an existing project, adapt the steps accordingly.
Create RedwoodJS App: Open your terminal and run:
Navigate to Project Directory:
Install Plivo Node.js SDK: Install the official Plivo helper library specifically into the
api
workspace.Why
yarn workspace api add
? RedwoodJS uses Yarn workspaces. This command ensures theplivo
package is added as a dependency only for the API side, where it's needed.Configure Environment Variables: Create a
.env
file in the root of your project. This file stores sensitive credentials and configuration securely, keeping them out of version control.Add the following variables to your
.env
file:How to get these values:
PLIVO_AUTH_ID
&PLIVO_AUTH_TOKEN
: Log in to your Plivo Console. Your Auth ID and Auth Token are displayed prominently on the main dashboard overview page.PLIVO_SENDER_ID
: This must be a Plivo phone number you have purchased or ported to your account. Navigate to Phone Numbers -> Your Numbers in the Plivo console.+14155551234
).Security: Ensure your
.env
file is listed in your.gitignore
file (RedwoodJS includes this by default) to prevent accidentally committing secrets.Note: RedwoodJS automatically loads variables from the
.env
file into the Node.jsprocess.env
object, making them accessible in your API-side code (likeprocess.env.PLIVO_AUTH_ID
).Project Structure: We will primarily work within the
api
directory:api/src/lib/logger.ts
: Redwood's built-in logger.api/src/services/
: Where our Plivo MMS service will reside.api/src/graphql/
: Where the GraphQL schema definition (SDL) for our mutation will live.api/src/functions/graphql.ts
: The main GraphQL endpoint handler (often requires no changes for basic service/SDL usage)..env
: Stores environment variables (already created).2. Implementing Core Functionality (Plivo Service)
We'll create a RedwoodJS service to encapsulate the logic for sending MMS messages via Plivo.
Generate the Service: Use the Redwood CLI to generate the service files:
This creates:
api/src/services/plivoMms/plivoMms.ts
: The service logic file.api/src/services/plivoMms/plivoMms.scenarios.ts
: For seeding data during tests.api/src/services/plivoMms/plivoMms.test.ts
: The unit test file.Implement the
sendMms
Function: Openapi/src/services/plivoMms/plivoMms.ts
and replace its contents with the following:SendMmsArgs
,SendMmsResponse
) for better code clarity and safety.to
,mediaUrl
).logger
for different levels (info, warn, error, debug) to aid troubleshooting.try...catch
block and returns a structured response indicating success or failure, including potential error messages from Plivo.text: ' '
: Plivo's API often requires thetext
field even for MMS. Sending a single space satisfies this requirement if no specific text is provided.media_urls
: Note the parameter name used by the Plivo Node.js SDK ismedia_urls
, expecting an array of strings.3. Building a Complete API Layer (GraphQL)
Now, let's expose our
sendMms
service function through the RedwoodJS GraphQL API.Define the GraphQL Mutation (SDL): Create a new file
api/src/graphql/plivoMms.sdl.ts
and add the following schema definition:PlivoMmsResponse
Type: Defines the structure of the data returned by the mutation. It mirrors theSendMmsResponse
interface from our service.sendPlivoMms
Mutation: Defines the mutation name, its input arguments (to
,mediaUrl
,text
), and the response type (PlivoMmsResponse!
).to: String!
: Recipient number (required).mediaUrl: String!
: Media URL (required).text: String
: Optional text body.@requireAuth
: This directive enforces that the user must be authenticated to call this mutation. Change to@skipAuth
if this specific mutation should be publicly accessible, but be cautious about potential abuse. Adjust authentication based on your application's needs. Redwood automatically wires this SDL definition to the corresponding service function (sendMms
inplivoMms.ts
).Testing with GraphQL Playground: Once you run
yarn rw dev
, RedwoodJS provides a GraphQL Playground (usually athttp://localhost:8911/graphql
) where you can test this mutation.Example Mutation Request:
Expected Success Response (Example):
Expected Failure Response (Example - Invalid Number):
Expected Failure Response (Example - Plivo API Error):
4. Integrating with Plivo (Configuration Recap)
This section summarizes the critical Plivo configuration steps already covered.
Auth ID
andAuth Token
..env
file asPLIVO_AUTH_ID
andPLIVO_AUTH_TOKEN
. Never commit these to version control.+14155551234
)..env
file asPLIVO_SENDER_ID
.mediaUrl
you provide must be publicly accessible over the internet. Plivo's servers need to fetch the media from this URL to attach it to the MMS. Private or localhost URLs will not work.5. Error Handling, Logging, and Retry Mechanisms
sendMms
) implements basic error handling:.env
variables).to
format,mediaUrl
format).try...catch
block around theclient.messages.create
call to capture exceptions from the Plivo SDK or API.SendMmsResponse
object containingsuccess: false
and anerror
message upon failure.logger
is used:logger.info
: Records initiation attempts and successful queuing.logger.warn
: Records non-critical issues like invalid input formats before attempting the API call.logger.error
: Records exceptions caught during the Plivo API interaction, including the error object.logger.debug
: Can be used for more verbose logging during development (e.g., logging the exact params sent to Plivo). Adjust log levels inapi/src/lib/logger.ts
or via environment variables (LOG_LEVEL
) for different environments.async-retry
can simplify this.sendMms
function):bail
function inasync-retry
to prevent retries for such cases.6. Database Schema and Data Layer
For this specific task of sending an MMS, a database isn't strictly required by the core Plivo integration itself. However, in a real-world application, you would likely want to:
messageUuid
returned by Plivo along with recipient details, timestamp, and initial status (queued
).sent
,delivered
,failed
). You'd need:MessageLog
schema).MessageLog
table using themessageUuid
.Example Prisma Schema (Conceptual):
Implementing the webhook handler and database logging is beyond the scope of this initial setup guide but is a recommended enhancement for production applications.
7. Security Features
Auth ID
andAuth Token
are stored securely in.env
and accessed as environment variables..env
is excluded from Git via.gitignore
.sendMms
service performs basic checks on theto
number format (E.164) andmediaUrl
format. Robust validation (e.g., using a library likelibphonenumber-js
for phone numbers) is recommended for production.text
input if it originates directly from users to prevent injection attacks (though less critical when sending out via Plivo, still good practice).sendPlivoMms
uses@requireAuth
(by default). Ensure your RedwoodJS app has authentication set up (yarn rw setup auth ...
) if needed. Only authenticated and authorized users should be able to trigger MMS sends if the action is tied to user activity.@skipAuth
), implement other safeguards like API keys or stricter rate limiting.sendPlivoMms
mutation.mediaUrl
values does not allow users to input arbitrary URLs pointing to internal resources or malicious sites. Validate the source of media URLs.8. Handling Special Cases
dst
) numbers in E.164 format (+
followed by country code and number, e.g.,+14155551234
). Ensure your frontend or backend properly formats numbers before passing them to the service.mediaUrl
must be publicly accessible. Plivo needs to download the content. Localhost URLs, URLs behind firewalls, or URLs requiring authentication will not work. Consider using cloud storage (like AWS S3, Google Cloud Storage) with public read access for the media files.9. Performance Optimizations
For sending single MMS messages triggered by user actions, performance is usually less critical than reliability. However, consider:
async/await
). ThesendMms
function returns quickly after queueing the message with Plivo; it doesn't wait for final delivery.messages.create
API sends one message per request. For high-volume sending, investigate Plivo's Powerpack feature or bulk messaging capabilities if available, which might offer more optimized throughput, though potentially with different API interactions.mediaUrl
points) is performant and scalable to handle Plivo fetching the files quickly. Using a Content Delivery Network (CDN) for media files is recommended.10. Monitoring, Observability, and Analytics
logger
. Ensure logs are aggregated in your production environment (e.g., using services like Datadog, Logtail, Papertrail, or cloud provider logging). Monitor logs for error patterns (level: 'error'
orlevel: 'warn'
).Queued
,Sent
,Delivered
,Failed
,Undelivered
), troubleshoot delivery issues, and view costs. Filter bymessageUuid
.yarn rw setup monitoring ...
)./health
) that verifies database connectivity and potentially checks if essential environment variables (PLIVO_...
) are loaded.sendPlivoMms
GraphQL mutation (request rate, error rate, duration) using your Application Performance Monitoring (APM) tool or logging platform.11. Troubleshooting and Caveats
Authentication credentials invalid
PLIVO_AUTH_ID
orPLIVO_AUTH_TOKEN
in.env
..env
. Ensure the environment variables are correctly loaded in your deployment environment.Invalid 'src' parameter
orThis caller ID is not allowed...
PLIVO_SENDER_ID
in.env
is not a valid Plivo number associated with your account, is not MMS-enabled, or is potentially of a type not allowed for sending MMS (e.g., a short code not provisioned for MMS).Invalid 'dst' parameter
orDestination number is not valid for MMS
to
number is not in valid E.164 format, or you are attempting to send MMS outside the US/Canada.to
number starts with+
and country code. Verify the recipient is in the US or Canada.Media URL could not be downloaded
or similar media errormediaUrl
provided is not publicly accessible, is malformed, points to an unsupported file type, or exceeds size limits.Sent
orDelivered
)Failed
orUndelivered
..env
variables are correctly configured in your hosting provider's environment variable settings (Vercel, Netlify, Render, etc.). Do not commit the.env
file.12. Deployment and CI/CD
Deploying your RedwoodJS application with Plivo integration follows standard Redwood procedures, with a key focus on environment variables.
.env
file:PLIVO_AUTH_ID
PLIVO_AUTH_TOKEN
PLIVO_SENDER_ID
.env
file to Git. Use the hosting provider's mechanism for managing secrets.yarn rw build
.