Frequently Asked Questions
Use NestJS with MessageBird's Batch SMS API. Create a NestJS service to interact with the API, define DTOs for validation, and set up a controller endpoint to handle requests. This allows sending multiple messages in a single API call, improving efficiency for large-scale SMS needs.
MessageBird's Batch SMS API lets you send many unique SMS messages to different people with one API request. This is far more efficient than sending individual messages, especially for large volumes, and is ideal for applications needing notifications, alerts, or marketing outreach.
NestJS provides a robust framework with features like dependency injection, modularity, and TypeScript support, making it suitable for building scalable applications. This structure simplifies integrating third-party services like MessageBird and managing complex logic for reliable bulk SMS sending.
Install the required packages, including @nestjs/axios
, messagebird
, and @nestjs/config
, then create a messaging module and service. In the module, use HttpModule.registerAsync
with ConfigService
to inject your API key and endpoint from environment variables for secure configuration.
Prisma is used as an Object-Relational Mapper (ORM) to simplify database interactions. It makes it easier to log bulk SMS requests, responses, and other relevant data, improving tracking and monitoring capabilities within your NestJS application.
Create a .env
file in your project root. Add MESSAGEBIRD_ACCESS_KEY
(your API key from the MessageBird dashboard) and MESSAGEBIRD_API_ENDPOINT
. The project uses @nestjs/config
to load these variables, and it's crucial to add .env
to your .gitignore
file to prevent exposing your credentials.
The @nestjs/throttler
package helps prevent abuse and overload by limiting API requests. In this bulk SMS system, it protects the MessageBird API from excessive calls, ensuring service stability and preventing potential issues due to rate limits.
The endpoint (POST /messages/bulk
) expects a JSON object with a "messages" array. Each element in this array represents an individual message with "recipients", "originator", and "body" properties. Validation is handled by DTOs to ensure correct data format and prevent invalid requests.
It's critical to secure this endpoint using API keys, JWT, or other authentication methods. An API key guard is recommended to control access and prevent unauthorized usage of the endpoint in a real-world application.
The MessagingService
implements retry logic with exponential backoff for transient errors (5xx status codes). It throws HttpExceptions for both retryable and non-retryable errors. The controller catches these exceptions and returns appropriate error responses to the client.
You'll need Node.js v16+, npm/pnpm/yarn, a MessageBird account and API key, a PostgreSQL database (or other Prisma-supported database), and basic knowledge of NestJS, TypeScript, and REST APIs. The guide provides instructions for setting up the project, dependencies, and configuration.
The BulkMessagesDto validates incoming requests to ensure no more than 100 messages are included per batch request. This limit aligns with typical API constraints and helps manage resource usage and response times.
Use the test API key from your MessageBird dashboard during development to avoid sending real messages and incurring costs. Switch to the live API key for production when you're ready to send actual bulk SMS messages.
The provided code includes a simplified response interface. Refer to the official MessageBird API documentation for the complete response structure and handle different status codes and fields accordingly in your application.
Yes, you can customize the API endpoint by setting the MESSAGEBIRD_API_ENDPOINT
environment variable. The default is https://rest.messagebird.com
, but you might need to change it if you are using a different MessageBird environment or region.
Build a Bulk SMS Broadcasting System with MessageBird and NestJS
Bulk SMS broadcasting lets you send promotional campaigns, alerts, or notifications to thousands of recipients efficiently. This guide shows you how to build a production-ready bulk SMS system using MessageBird's SMS API and NestJS.
Important Note: MessageBird's standard
/messages
API endpoint accepts a maximum of 50 recipients per request according to their official documentation. For larger volumes, you'll need to batch requests on the application side or verify with MessageBird support about enterprise batch endpoints. Always consult the latest MessageBird API documentation for current limits and features.What You'll Build with MessageBird and NestJS
By the end of this tutorial, you'll have a NestJS application that:
Prerequisites for MessageBird NestJS Integration
Before you begin, ensure you have:
Step 1: Set Up Your NestJS Project for MessageBird Integration
Create a new NestJS project:
Install the required dependencies:
Dependency breakdown:
@nestjs/config
– Manages environment variables@nestjs/axios
– HTTP client module for MessageBird API calls@nestjs/throttler
– Rate limiting to prevent API abuse@prisma/client
andprisma
– Database ORM for PostgreSQLaxios
– HTTP library (peer dependency for @nestjs/axios)Step 2: Configure MessageBird API Environment Variables
Create a
.env
file in your project root:Replace
your_messagebird_api_key_here
with your actual MessageBird API key from the MessageBird Dashboard.Update
src/app.module.ts
to load environment variables:Step 3: Set Up Prisma Database Schema for SMS Campaign Tracking
Initialize Prisma:
This command creates a
prisma
directory with aschema.prisma
file. Update it to define your SMS campaign and message models:Schema explanation:
SmsCampaign
– Stores campaign metadata, total message count, and success/failure talliesSmsMessage
– Tracks individual messages with recipient, status, and MessageBird response datacampaignId
Generate the Prisma client and run migrations:
Step 4: Create DTOs for MessageBird SMS Request Validation
NestJS uses Data Transfer Objects (DTOs) with class-validator decorators to validate incoming requests.
Create
src/sms/dto/create-bulk-sms.dto.ts
:Key validations:
Step 5: Build the MessageBird SMS Service with Retry Logic
Create
src/sms/sms.service.ts
to handle MessageBird API interactions, retry logic, and database persistence:Key features:
Step 6: Create the NestJS SMS Controller with Rate Limiting
Create
src/sms/sms.controller.ts
to expose REST endpoints:Step 7: Create the Prisma Service Module
Create
src/prisma/prisma.service.ts
:Create
src/prisma/prisma.module.ts
:Step 8: Wire Up the SMS Module
Create
src/sms/sms.module.ts
:Update
src/app.module.ts
:Step 9: Test Your MessageBird Bulk SMS Integration
Start your NestJS application:
Send a test bulk SMS request:
Expected response:
Check campaign status:
Production Considerations for MessageBird SMS at Scale
1. Environment Variables Security
Store sensitive credentials securely:
.env
files to version control2. Rate Limiting Strategy
MessageBird enforces API rate limits (500 POST requests/second per official documentation). Implement application-level rate limiting:
For high-volume campaigns, use a queue system (BullMQ, AWS SQS) to throttle requests.
3. Message Queuing for Large Campaigns
For campaigns exceeding 10,000 messages, integrate a job queue:
Update
sms.service.ts
to queue messages:4. Monitoring and Logging
Integrate application performance monitoring (APM):
Add structured logging:
5. Compliance and Consent Management
Ensure legal compliance:
Store consent timestamps in your database:
6. Cost Optimization
MessageBird charges per message segment:
Optimize message length:
Display segment count in your API response to help users optimize costs.
Troubleshooting MessageBird NestJS Integration Issues
1. "Invalid phone number format" Error
Cause: Phone numbers must be in E.164 format (+[country code][number]).
Fix: Validate numbers before sending:
2. Rate Limit 429 Errors
Cause: Exceeding MessageBird's rate limits (500 POST requests/second).
Fix: Implement exponential backoff (already included in the service above) or use a queue system to throttle requests.
3. Messages Not Delivering
Possible causes:
Debug steps:
4. Database Connection Issues
Cause: Incorrect
DATABASE_URL
in.env
file.Fix: Verify PostgreSQL connection string format:
Test connection:
Frequently Asked Questions (FAQ)
How many recipients can I send to in a single MessageBird API request?
MessageBird's standard
/messages
endpoint accepts a maximum of 50 recipients per request according to their official documentation. For campaigns exceeding 50 recipients, you'll need to batch requests on the application side (as demonstrated in this tutorial) or contact MessageBird support about enterprise batch endpoints. The code example above automatically handles batching by looping through messages.What is MessageBird's rate limit for SMS API requests?
MessageBird enforces a rate limit of 500 POST requests per second for SMS messaging according to their official documentation. The NestJS service in this tutorial includes exponential backoff retry logic to handle 429 (rate limit) errors automatically. For high-volume campaigns, implement a queue system like BullMQ to throttle requests and stay within limits.
How do I handle MessageBird API failures and retry logic in NestJS?
The tutorial's
SmsService
includes asendWithRetry()
method with exponential backoff. It automatically retries failed requests up to 3 times with increasing delays (1s, 2s, 4s). The service retries on 429 (rate limit) and 5xx (server error) status codes. All failed messages are logged to the database with error details for monitoring.What database schema do I need for MessageBird bulk SMS campaigns?
The Prisma schema includes two models:
SmsCampaign
(stores campaign metadata, success/failure counts) andSmsMessage
(tracks individual messages with recipient, status, and MessageBird response data). This schema enables campaign tracking, delivery reports, and historical analytics. Runnpx prisma migrate dev
to create the tables.How do I validate phone numbers for MessageBird SMS API?
MessageBird requires phone numbers in E.164 format (e.g., +14155552671). The tutorial uses class-validator with a regex pattern
/^\+[1-9]\d{1,14}$/
to validate E.164 format. For production, consider usinglibphonenumber-js
library for more robust validation including country code verification and number type detection.Can I send Unicode (emoji) messages through MessageBird?
Yes, MessageBird supports Unicode messages using UCS-2 encoding. However, Unicode messages have a reduced character limit of 70 characters per segment (vs. 160 for GSM-7). The tutorial's DTO allows up to 1,600 characters (10 concatenated segments). Calculate costs carefully – Unicode messages consume more segments and cost more.
How do I implement MessageBird delivery status webhooks in NestJS?
Create a new controller endpoint to receive MessageBird delivery reports. Configure the webhook URL in your MessageBird dashboard under "Developers > Webhooks." MessageBird sends POST requests with delivery status updates (delivered, failed, expired). Parse the webhook payload and update your
SmsMessage
records in the database accordingly.What NestJS modules do I need for MessageBird SMS integration?
The core dependencies are:
@nestjs/config
(environment variables),@nestjs/axios
(HTTP client for MessageBird API),@nestjs/throttler
(rate limiting),@prisma/client
(database ORM), andaxios
(HTTP library). Install withnpm install @nestjs/config @nestjs/axios @nestjs/throttler @prisma/client axios
. Additionally, installprisma
as a dev dependency for schema management.Next Steps: Enhance Your MessageBird NestJS SMS System
Now that you have a working bulk SMS system, consider these enhancements:
Additional Resources
Related Guides: