Frequently Asked Questions
Integrate MessageBird's MMS API into your RedwoodJS application by installing the MessageBird SDK, configuring environment variables with your access key and originator number, and creating a GraphQL mutation to trigger the sending process. This allows you to send multimedia messages like notifications and marketing content directly from your RedwoodJS project.
The MessageBird originator is the MMS-enabled phone number or approved alphanumeric sender ID used to send MMS messages. It must be in E.164 format (e.g., +12025550187) and associated with your MessageBird account. This is configured using the MESSAGEBIRD_ORIGINATOR environment variable in your RedwoodJS project.
While not strictly required for sending, a database helps track message details (recipient, status, media URLs, errors) for debugging, history, and potential future features. The Prisma schema defines an MmsMessage model to store these details, enabling efficient management and logging.
The example creates a database record with a 'pending' status before calling the MessageBird API. This approach allows tracking attempts even if the API call fails immediately. You can choose to create the record after successful API calls if preferred, but pre-creation aids in comprehensive logging.
MMS sending with MessageBird via a virtual mobile number is currently limited to the US and Canada for the number originator. Check the MessageBird documentation for updates and potential use of Alphanumeric Sender IDs. Ensure your recipient numbers are in the correct international format.
Navigate to your RedwoodJS project directory and run yarn workspace api add messagebird. This installs the necessary SDK within the API side of your project, allowing you to interact with the MessageBird API for sending MMS messages.
Prisma is used for database interactions, specifically for creating and updating records in the MmsMessage table. This table stores the details of each MMS message, including recipient, status, media URLs, and any error messages encountered during the sending process. Prisma simplifies database operations within your RedwoodJS application.
Set up a webhook handler function in your RedwoodJS API to receive status updates from MessageBird. MessageBird sends these updates as GET requests to your configured URL, containing parameters like message ID, status, and recipient. You can then update the corresponding record in your database to reflect the current message status.
Store your MessageBird access key as an environment variable in a .env file located in the root of your RedwoodJS project. Ensure that this file is added to your .gitignore to prevent it from being committed to version control, protecting your API credentials.
MessageBird's MMS API has a limit of 10 media attachments per message. The provided service implementation includes validation to prevent exceeding this limit. Ensure your attached media files are publicly accessible URLs and adhere to MessageBird's size and format requirements.
The @requireAuth
directive on the sendMms mutation ensures only logged-in users can initiate MMS sending. This basic access control prevents unauthorized access and can be customized with role-based access control (RBAC) if needed. Remove or adjust it if your application does not require authentication.
RedwoodJS generates a test file where you can mock the MessageBird client and the database client using Jest. This allows you to simulate successful and failed API calls and verify the database interaction and error handling logic without actually sending MMS messages. Use yarn rw test api to run tests.
The provided service implementation uses a try...catch block to handle errors during API calls. Errors are logged with details using Redwood's logger, the database record is updated with a 'failed' status and the error message, and then the error is re-thrown for the GraphQL layer to process. Consider implementing retry mechanisms with exponential backoff for transient errors.
Use environment variables for API keys, implement input validation and sanitization to protect against common web vulnerabilities, use pre-signed URLs with limited expiry for media attachments, and add rate limiting to your GraphQL mutation to prevent misuse and stay within MessageBird's limits.
Sending MMS with RedwoodJS and MessageBird
Learn how to integrate MessageBird's MMS API into your RedwoodJS application to send multimedia messages programmatically. This comprehensive guide walks you through building a production-ready MMS service with GraphQL mutations, media attachment handling, delivery status tracking, and webhook verification.
You'll build a complete MMS messaging solution using RedwoodJS's service layer architecture, Prisma ORM for database tracking, and the official MessageBird Node.js SDK. By the end, you'll have a fully functional system capable of sending MMS messages with images, videos, and audio files to US and Canadian phone numbers.
Target Audience: RedwoodJS developers and Node.js engineers implementing programmatic MMS messaging for notifications, marketing campaigns, or customer communication.
Prerequisites:
yarn create redwood-app ./my-mms-app
MMS Technical Specifications (MessageBird MMS API, Bird MMS Limits):
System Architecture:
1. Project Setup and Configuration
Before sending your first MMS message_ you'll need to install the MessageBird SDK and configure your RedwoodJS environment with API credentials.
Navigate to your project directory:
Install the MessageBird Node.js SDK: Install the SDK specifically in the
api
workspace.Package Version (January 2025): messagebird SDK (latest v4.0.1) supports Node.js >= 0.10, but RedwoodJS 8.x requires Node 20+. Ensure your environment uses Node 20 or higher.
Configure Environment Variables: RedwoodJS uses
.env
files for environment variables. Create or open the.env
file in the root of your project and add your MessageBird credentials and sender ID.MESSAGEBIRD_ACCESS_KEY
: Your API access key from the MessageBird Dashboard (Developers → API access). Treat this like a password and keep it secret. Use a live key for actual sending or a test key for development without incurring charges or sending real messages.MESSAGEBIRD_ORIGINATOR
: The MMS-enabled phone number in E.164 format (e.g.,+12025550187
). This number must be associated with your MessageBird account and enabled for MMS. US/Canada numbers only support MMS sending (as of January 2025).MESSAGEBIRD_SIGNING_KEY
: Your signing key for webhook signature verification. Find this in the MessageBird Dashboard under Developers → Settings. This ensures webhook requests are authentic.Ensure Environment Variables are Loaded: RedwoodJS automatically loads variables from
.env
intoprocess.env
. No further action is needed for them to be accessible in the API side.2. Database Schema for Message Tracking
Tracking MMS delivery status is essential for production applications. Store message details in your database using Prisma to enable delivery tracking, debugging, and message history queries.
Define the Prisma Schema: Open
api/db/schema.prisma
and add the following model:messageBirdId
: Stores the unique ID returned by MessageBird upon successful sending, allowing you to correlate updates later. Marked as optional initially as it's only available after a successful API call.mediaUrls
: Prisma supports string arrays, suitable for storing the list of media URLs.status
: Tracks the message lifecycle. Initialized aspending
.Apply Schema Changes (Database Migration): Run the following command to create and apply a new database migration:
Follow the prompts to name your migration (e.g.,
add_mms_message_model
).3. Building the GraphQL API Layer
Create a GraphQL mutation to expose MMS sending functionality to your frontend application. This mutation will accept recipient details, message content, and media URLs.
Generate GraphQL and Service Files: Use the Redwood generator to scaffold the necessary files for an
mms
resource.This command creates:
api/src/graphql/mms.sdl.ts
: Defines the GraphQL schema types and operations.api/src/services/mms/mms.ts
: Contains the business logic (service functions).api/src/services/mms/mms.scenarios.ts
: For database seeding during tests.api/src/services/mms/mms.test.ts
: For writing unit tests.Define the
sendMms
Mutation: Modifyapi/src/graphql/mms.sdl.ts
to define a specific mutation for sending MMS. Remove the generated CRUD operations for now and add thesendMms
mutation.MmsMessage
type mirrors the Prisma model.SendMmsInput
specifies the required data: recipient number, optional subject/body, and an array of media URLs. At leastbody
ormediaUrls
must be provided in the actual MessageBird API call.sendMms
mutation takes this input and returns theMmsMessage
record created in the database.@requireAuth
: This directive ensures only authenticated users can call this mutation. Adjust or remove based on your application's auth requirements.4. Implementing the MMS Service Logic
Implement the core MMS sending logic in your RedwoodJS service layer. This service will handle MessageBird API calls, input validation, error handling, and database updates.
Edit the MMS Service: Open
api/src/services/mms/mms.ts
and replace its contents with the following:Explanation:
validate
,logger
,db
), andinitClient
frommessagebird
.messagebird
client is initialized outside the function using theMESSAGEBIRD_ACCESS_KEY
from environment variables. This reuses the client instance.MESSAGEBIRD_ORIGINATOR
is configured.mmsParams
object matching the structure required bymessagebird.mms.create
. Note thatrecipients
must be an array. Added unique reference ID for tracking.MmsMessage
table before calling the API with apending
status. This helps track attempts even if the API call fails immediately.messagebird.mms.create
call in aPromise
because the SDK uses a callback pattern. This allows usingasync/await
.messageBirdId
returned by the API and set the status tosent
.try...catch
block catches errors from input validation or the API call promise rejection. Extract meaningful error messages from the caughterror
object. Update database record withfailed
status and error message. Re-throw error to signal failure to GraphQL layer.5. MessageBird API Integration Details
Understanding how to authenticate and structure API requests ensures reliable MMS delivery. The MessageBird SDK handles most complexity, but proper configuration is essential.
initClient(process.env.MESSAGEBIRD_ACCESS_KEY)
. Ensure the key is correct and has the necessary permissions in your MessageBird account.https://rest.messagebird.com/mms
).SendMmsInput
to the requiredmessagebird.mms.create
parameters:originator
: Fromprocess.env.MESSAGEBIRD_ORIGINATOR
.recipients
: Takesinput.recipient
and puts it in an array[input.recipient]
.subject
: Frominput.subject
.body
: Frominput.body
.mediaUrls
: Frominput.mediaUrls
. Ensure these are publicly accessible URLs. MessageBird needs to fetch them. They must also adhere to size (1 MB max per file, 900 KB total recommended) and type constraints as documented in MessageBird MMS API..env
is the standard way to handle API keys securely in RedwoodJS. Never commit your.env
file to version control. Use.env.defaults
for non-sensitive defaults and add.env
to your.gitignore
file.Obtaining MessageBird Credentials:
+1...
).6. Error Handling and Retry Strategies
Robust error handling prevents message loss and provides actionable debugging information. Understanding MessageBird error codes helps you implement appropriate retry logic.
try...catch
to capture exceptions during the process. Errors are logged, and the corresponding database record is updated with a 'failed' status and an error message. The error is then re-thrown to the GraphQL layer.logger
(pino
) is used to log informational messages (API call attempts, success) and errors. Check your console output when runningyarn rw dev
or your production log streams. Logged objects ({ err }
,{ response }
) provide detailed context. MessageBird API error responses often contain anerrors
array with specificcode
,description
, andparameter
fields.async-retry
can help implement strategies like exponential backoff. This typically involves catching specific error types/codes and scheduling a background job (using RedwoodJS background functions or external queues like Redis/BullMQ) to retry thesendMms
operation after a delay.7. Security Best Practices
Securing your MMS integration prevents unauthorized access, protects API credentials, and ensures compliance with messaging regulations.
@requireAuth
directive on thesendMms
mutation ensures only logged-in users can trigger it. Implement role-based access control if needed (e.g., only admins can send certain types of MMS).@redwoodjs/api
'svalidate
function and custom checks:subject
,body
) if they are displayed elsewhere in your application to prevent XSS attacks. Libraries likedompurify
(if rendering HTML) or simple replacements can help..env
and not committing it is paramount. Use secrets management solutions (like Doppler, Vercel environment variables, AWS Secrets Manager) in production environments.graphql-rate-limit-directive
) to prevent abuse and hitting MessageBird limits.mediaUrls
provided point to trusted sources. If users upload media, use secure storage (like S3, GCS) and consider pre-signed URLs with limited expiry times passed to the mutation, rather than directly public URLs if possible. Validate file types and sizes during upload.8. Testing Your MMS Integration
Thorough testing validates your implementation before deploying to production. Test both successful sends and error scenarios to ensure reliability.
Unit Testing the Service: RedwoodJS generates a test file (
api/src/services/mms/mms.test.ts
). Modify it to test thesendMms
logic. Mock themessagebird
client and thedb
client.Run tests using
yarn rw test api
.Manual Verification (Development):
Start the development server:
yarn rw dev
.Open the GraphQL Playground, usually at
http://localhost:8911/graphql
.Ensure your
.env
file has valid Test or Live credentials and a valid MMS-enabled Originator Number.Execute the
sendMms
mutation:Checklist:
yarn rw dev
output) for logs. Are there errors?yarn rw prisma studio
) – was anMmsMessage
record created? Does it have amessageBirdId
andsent
status (if successful) orfailed
status and an error message?9. Webhook Setup for Delivery Status Updates
Receive real-time delivery status updates from MessageBird using webhooks. Proper JWT signature verification ensures webhook authenticity and prevents spoofing attacks.
Create a Webhook Handler Function: Use the Redwood generator to create an HTTP function.
Implement the Handler with JWT Signature Verification: Edit
api/src/functions/messagebirdWebhook.ts
. MessageBird sends status updates via GET requests with a JWT signature header per MessageBird API documentation.Key Security Enhancements:
RequestValidator
to verify theMessageBird-Signature-JWT
header per MessageBird webhook documentation. This ensures requests are authentic and haven't been tampered with.MESSAGEBIRD_SIGNING_KEY
from environment variables (obtained from MessageBird Dashboard → Developers → Settings).Configure Webhook in MessageBird Dashboard:
https://your-domain.com/.redwood/functions/messagebirdWebhook
).Testing Webhooks Locally: Use a service like ngrok to expose your local development server:
Copy the HTTPS URL provided by ngrok and configure it as your webhook URL in MessageBird Dashboard (append
/.redwood/functions/messagebirdWebhook
to the ngrok URL).10. Deploying to Production
Prepare your MMS integration for production with proper environment configuration, monitoring, and security measures.
Environment Variables: Set all required environment variables (
MESSAGEBIRD_ACCESS_KEY
,MESSAGEBIRD_ORIGINATOR
,MESSAGEBIRD_SIGNING_KEY
) in your hosting platform (Vercel, Netlify, AWS, etc.).Database Migration: Run Prisma migrations in production:
HTTPS Required: MessageBird webhooks require HTTPS endpoints. Ensure your production deployment uses SSL/TLS certificates.
Rate Limiting: Implement application-level rate limiting to prevent abuse and stay within MessageBird's API limits. US/Canada numbers have a daily limit of 500 SMS per day per number as documented in MessageBird number restrictions.
Monitoring and Logging: Set up proper logging and monitoring for production. Use services like Datadog, Sentry, or LogRocket to track errors and performance.
Webhook Endpoint Security: Ensure your webhook endpoint:
Background Job Queue: For high-volume MMS sending, consider implementing a background job queue using RedwoodJS background jobs or external systems like BullMQ/Redis to avoid timeouts and improve reliability.
Cost Management: Monitor MMS costs. Pricing varies by country and carrier. Check Bird SMS/MMS pricing for current rates (typically $0.0075-$0.015 per SMS segment in the US, MMS costs more).
Summary: Your Complete MMS Integration
Congratulations! You've built a production-ready MessageBird MMS integration for RedwoodJS with:
Next Steps:
Related Guides:
External Resources: