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
This guide provides a step-by-step walkthrough for integrating MessageBird's MMS API into a RedwoodJS application. We'll build a backend service capable of sending MMS messages, including media attachments, track their basic status, and handle necessary configurations securely. This enables developers to add rich media messaging capabilities to their RedwoodJS projects, suitable for notifications, marketing, or user communication.
We will utilize RedwoodJS for its integrated structure (API and web sides), Prisma for database interactions, and the official MessageBird Node.js SDK. By the end, you'll have a functional GraphQL mutation to send MMS messages and a basic setup for tracking them.
Target Audience: Developers familiar with RedwoodJS and Node.js looking to implement programmatic MMS sending.
Prerequisites:
yarn create redwood-app ./my-mms-app
System Architecture:
1. Project Setup and Configuration
First_ we need to install the MessageBird SDK and configure our RedwoodJS environment.
Navigate to your project directory:
Install the MessageBird Node.js SDK: Install the SDK specifically in the
api
workspace.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
) or potentially an approved Alphanumeric Sender ID (check MessageBird documentation and country restrictions – US/CA generally require a number for MMS). This number must be associated with your MessageBird account and enabled for MMS.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 Tracking Messages
While not strictly necessary just to send an MMS, storing message details is crucial for tracking, debugging, and displaying history. We'll use Prisma to define a simple model.
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 us 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 API Layer (GraphQL)
We'll create a GraphQL mutation to trigger the MMS sending process.
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. We'll remove the generated CRUD operations for now and add oursendMms
mutation.MmsMessage
type mirroring our 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, which we'll enforce in the service.sendMms
mutation takes this input and returns theMmsMessage
record created in our database.@requireAuth
: This directive ensures only authenticated users can call this mutation. Adjust or remove based on your application's auth requirements.4. Implementing Core Functionality (MMS Service)
Now, we implement the logic within the service function to interact with the MessageBird API.
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.recipient
,mediaUrls
) and the MessageBird limit on media attachments. Also checks that eitherbody
ormediaUrls
are present.MESSAGEBIRD_ORIGINATOR
is configured.mmsParams
object matching the structure required bymessagebird.mms.create
. Note thatrecipients
must be an array.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 us to useasync/await
.err
andresponse
from MessageBird. On error, the promise is rejected; on success, it's resolved with the response.messageBirdId
returned by the API and set the status tosent
. We return the updated record.try...catch
block catches errors either from input validation or the API call promise rejection.error
object (MessageBird errors often have a.errors
array).failed
status and the error message.5. Integrating with MessageBird (Service Details Revisited)
The core integration happens within the
sendMms
service function: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 (under 1MB each typically) and type constraints (see MessageBird MMS docs for supported types like JPEG, PNG, GIF, MP4, etc.)..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, Logging, and Retries
Our service includes basic error handling and logging:
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, which are invaluable for debugging.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 Considerations
@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 (e.g., body/media presence, media count). You could add more specific validation for phone number formats (e.g., usinglibphonenumber-js
) or URL formats.subject
,body
) if they are displayed elsewhere in your application to prevent XSS attacks. Libraries likedompurify
(if rendering HTML) or simple replacements can help. For this API-only interaction, the risk is lower..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
Testing ensures the service behaves as expected.
Unit Testing the Service: RedwoodJS generates a test file (
api/src/services/mms/mms.test.ts
). Modify it to test thesendMms
logic. We need to 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. Handling Status Updates (Webhook - Optional but Recommended)
To get delivery statuses (
delivered
,failed
, etc.) back from MessageBird, you need to set up a webhook.Create a Webhook Handler Function: Use the Redwood generator to create an HTTP function.
Implement the Handler: Edit
api/src/functions/messagebirdWebhook.ts
. MessageBird sends status updates via GET requests to your configured URL.