Frequently Asked Questions
You can send SMS messages in a RedwoodJS application by creating a GraphQL mutation that interacts with the MessageBird API. This involves setting up a service to handle the API call logic and defining the mutation in your GraphQL schema. The provided code example uses the MessageBird Node.js SDK to simplify the integration.
MessageBird is a communication platform that provides the SMS API and virtual phone numbers for sending and receiving text messages within your RedwoodJS application. This allows you to add features like notifications, alerts, and customer support interactions via SMS.
ngrok creates a temporary public URL that tunnels HTTP traffic to your local RedwoodJS development server. This is necessary during development so MessageBird's webhook can reach your locally running messagebirdWebhook
function to test incoming SMS messages before deploying to production.
Verifying the MessageBird webhook signature is crucial for security and should always be done, especially in production. This step confirms that incoming webhook requests genuinely originate from MessageBird and haven't been tampered with.
Yes, but be aware of character limits. Standard SMS (GSM-7) allows 160 characters. Using emojis or non-standard characters switches to UCS-2 encoding, reducing the limit to 70 characters. MessageBird handles concatenation for longer messages, but they're billed as multiple parts.
Incoming SMS messages are handled by creating a RedwoodJS function, which acts as a webhook endpoint. This function receives POST requests from MessageBird, verifies the signature, parses the message data, and then processes it (e.g., logging, triggering actions).
A RedwoodJS function serves as the webhook endpoint for receiving incoming SMS messages from MessageBird. It handles the incoming HTTP requests, signature verification, and processing of the received SMS data.
MessageBird requires a 200 OK response from your webhook to acknowledge successful receipt of the message. Failure to respond quickly or returning an error can cause MessageBird to retry sending the webhook, potentially leading to duplicate processing.
If processing inbound SMS messages involves time-consuming operations (database writes, external API calls), perform them asynchronously after returning a 200 OK to MessageBird. This keeps your webhook responsive and prevents MessageBird from retrying.
The MessageBird Node.js SDK provides a webhooks.verify
function for signature verification. Your webhook function must check if the signature is missing from the request, compare it against the signing key (stored securely in environment variables) and return a 401 error if there is an issue with the signature.
The MessageBird originator number is your provisioned virtual phone number, used as the sender ID for outbound messages and the number users reply to for inbound messages. It must be in E.164 format (e.g., +14155552671).
You can store SMS message logs using Prisma, RedwoodJS's ORM. Define a model in your schema.prisma
file to represent the message data (direction, originator, recipient, body, status, etc.) and then use db.messageLog.create
in your service and function to save the message details.
E.164 (+14155552671) ensures consistent, internationally recognized phone number formatting, crucial for reliable SMS delivery and routing. MessageBird strongly recommends using E.164.
Carriers often mandate handling keywords like STOP, HELP, INFO. Check MessageBird's documentation, sometimes they handle opt-out logic with a STOP keyword. Implement logic in your webhook to process HELP messages (e.g., by sending an automated reply) and to update your database with user preferences if a user texts STOP, preventing future communication.
Build Two-Way SMS Messaging in RedwoodJS with MessageBird
Build production-ready two-way SMS functionality into your RedwoodJS application using the MessageBird API and Node.js SDK. Send outbound SMS messages and receive inbound messages via webhooks to enable powerful communication features.
This guide covers initial project setup, secure API key management, core logic implementation, webhook handling with signature verification, message logging, and deployment. You'll have a robust system for interacting with users via SMS.
Project Overview and Goals
What You'll Build:
A RedwoodJS application that:
Problem Solved:
Enable direct, reliable SMS communication channels within your application for notifications, alerts, user verification, customer support interactions, or any feature requiring SMS messaging.
Technologies Used:
ngrok
(development): Exposes local development server to the internet for testing incoming webhooks.Architecture:
Prerequisites:
yarn global add redwoodjs@latest
ngrok
or similar tunneling tool for local development webhook testingExpected Outcome:
A functional RedwoodJS application demonstrating SMS sending via GraphQL mutation and receiving/logging incoming SMS via webhook, ready for further feature integration and deployment.
1. Setting up the Project
Let's initialize a new RedwoodJS project and install necessary dependencies.
Create RedwoodJS Project: Open your terminal and run:
Using TypeScript provides better type safety and developer experience, especially for larger applications.
Install MessageBird SDK: Navigate to the
api
directory and add the MessageBird Node.js SDK:Configure Environment Variables: Sensitive information like API keys must never be committed to version control. We'll use environment variables.
Create a
.env
file in the project root (redwood-messagebird-app/.env
).Add the following lines, replacing placeholders later:
Explanation:
MESSAGEBIRD_ACCESS_KEY
: Your primary key for authenticating API requests to MessageBird. Found in your MessageBird Dashboard under Developer Settings -> API access. Use a live key for sending real messages, or a test key for simulation.MESSAGEBIRD_SIGNING_KEY
: Used to verify incoming webhook requests originate from MessageBird. Found in Developer Settings -> Webhook Signing. CRITICAL for security.MESSAGEBIRD_ORIGINATOR_NUMBER
: The MessageBird virtual number you purchased, which will be used as the sender ID for outbound messages and is the number users will text to for inbound messages. Must be in E.164 format (e.g.,+14155552671
).TEST_RECIPIENT_NUMBER
: Your personal mobile number for testing outbound messages.Add
.env
to.gitignore
: Ensure the root.gitignore
file contains.env
to prevent accidentally committing your keys. RedwoodJS's default.gitignore
should already include it.Accessing Environment Variables in RedwoodJS: RedwoodJS automatically loads variables from
.env
intoprocess.env
. You can access them in your API-side code (services, functions) likeprocess.env.MESSAGEBIRD_ACCESS_KEY
.2. Implementing Core Functionality (Outbound SMS)
Install the MessageBird SDK and create the core service for sending SMS messages.
Step 2.1: Install the MessageBird SDK
Navigate to your RedwoodJS project root directory and install the official MessageBird Node.js SDK:
Important: Use
yarn workspace api add
instead ofyarn add
to ensure the SDK installs into the API workspace (api/package.json
), not the rootpackage.json
.Step 2.2: Create the Outbound SMS Service
Generate a new service to encapsulate the outbound SMS logic:
This command creates
api/src/services/sms/sms.js
andapi/src/services/sms/sms.test.js
files.Configure the
sms.js
service:3. Building the API Layer (Inbound Webhook)
Handle incoming SMS messages through a webhook endpoint that receives and processes MessageBird notifications.
Step 3.1: Create the Webhook Handler Function
Generate a serverless function to handle incoming webhooks:
This creates
api/src/functions/webhook/webhook.js
.Implement the webhook handler:
4. Securing Your Implementation
Protect your webhook endpoint from unauthorized access and ensure message authenticity through signature verification.
Webhook Signature Verification
Verify every incoming webhook request using MessageBird's signing key. This prevents unauthorized requests and confirms message authenticity.
How signature verification works:
messagebird-signature
headerImplementation (already shown in webhook handler):
Best practices:
Environment Variable Security
Protect sensitive credentials by storing them as environment variables:
Security checklist:
.env
to.gitignore
to prevent committing secrets5. Database Schema and Message Logging
Store incoming and outgoing SMS messages in your database for tracking, analytics, and conversation history.
Step 5.1: Create the Prisma Schema
Define a
Message
model in your Prisma schema to store SMS data:Step 5.2: Apply Database Migrations
Run Prisma migrations to create the database table:
This command:
api/db/migrations/
Step 5.3: Query Messages
Use Prisma Client to query message history:
6. Testing Your Implementation
Validate your SMS integration thoroughly before deploying to production.
Testing Outbound SMS
Test the SMS sending functionality through your GraphQL API:
Verification steps:
Testing Inbound Webhooks Locally
Use ngrok to expose your local development server for webhook testing:
Step 1: Install and start ngrok:
Step 2: Configure MessageBird webhook:
https://abc123.ngrok.io
)https://abc123.ngrok.io/.redwood/functions/webhook
Step 3: Send test SMS:
Send an SMS from your phone to your MessageBird number. Monitor:
Simulating Webhook Requests
Test webhook handling without sending actual SMS messages using curl:
Note: This request will fail signature verification unless you calculate a valid signature. Temporarily disable signature verification for local testing only.
Common Testing Issues
Problem: Webhook receives requests but returns 401
Problem: Messages don't appear in database
.env
yarn rw prisma migrate dev
Problem: Outbound SMS fails with 401
Problem: ngrok tunnel disconnects
7. Deployment Considerations
Deploy your RedwoodJS SMS application with proper configuration for production environments.
Environment Variables
Configure production environment variables in your hosting platform:
Platform-specific configuration:
Webhook URL Configuration
Update your MessageBird webhook URL to point to your production domain:
https://your-domain.com/.redwood/functions/webhook
HTTPS Requirements
Use HTTPS for all webhook endpoints. MessageBird requires secure connections for webhook delivery.
Automatic HTTPS support:
Database Migrations
Apply database migrations before deploying new code:
Configure your CI/CD pipeline to run migrations automatically:
Monitoring and Logging
Implement monitoring to track SMS delivery and webhook processing:
Log critical events:
Recommended monitoring tools:
RedwoodJS logging configuration:
Rate Limiting
Implement rate limiting to prevent API abuse:
Conclusion
You have now successfully integrated two-way SMS messaging into your RedwoodJS application using MessageBird. You can send messages via a GraphQL mutation and receive incoming messages through a secure webhook function, with all communication logged to your database.
This foundation allows you to build various SMS-based features. Remember to prioritize security (especially webhook verification), handle errors gracefully, and consider the nuances of SMS communication like character limits and keyword handling.