Frequently Asked Questions
Use the Fastify framework with the MessageBird API and a Redis queue. The Fastify app receives SMS requests, adds them to a BullMQ job queue managed by Redis, and a background worker processes these jobs to send messages via the MessageBird API asynchronously.
The MessageBird Node.js SDK (@messagebird/api) simplifies interaction with the MessageBird REST API, making it easier to send SMS messages within your Node.js application. It handles the low-level details of making API calls, managing responses, and error handling.
Redis and BullMQ provide an asynchronous job queue system. This prevents blocking the main application thread when sending large volumes of SMS messages, improving responsiveness and scalability. BullMQ uses Redis as its message broker.
Prisma is optional but recommended for tracking message status. Use it if you need a robust way to persist message data (e.g., recipient, status, delivery reports) in a database like PostgreSQL.
Store your MessageBird API key securely in a .env file in your project's root directory. The provided code example uses dotenv to load environment variables, so your key will be available via process.env.MESSAGEBIRD_API_KEY. Never commit your .env file.
The example Fastify route includes error handling for queue failures using try-catch blocks around each addSmsJob call. Failed jobs are recorded and logged. The route is designed to continue processing and enqueueing other messages even if some queue additions fail.
The background worker listens to the Redis queue (using BullMQ) for new SMS sending jobs. It processes each job, extracting recipient and message data, and makes calls to the MessageBird API to send the actual SMS messages.
The worker example includes a limiter
option with max
and duration
to control the number of jobs processed within a specified time window. Adjust these values according to your MessageBird account's specific rate limits to avoid exceeding them.
The guide recommends Node.js v18 or later. This ensures compatibility with Fastify, BullMQ, the MessageBird SDK, and other dependencies.
You can use a purchased Virtual Mobile Number (VMN) or an Alphanumeric Sender ID (if available in your target region). VMNs allow two-way communication (receiving replies), while Alphanumeric IDs (e.g., company name) might have country restrictions and don't receive replies. Configure it using the MESSAGEBIRD_ORIGINATOR environment variable.
Fastify is a high-performance Node.js web framework. It is chosen for its speed, extensibility, and developer-friendly features like schema validation and logging, which make it suitable for building robust and scalable APIs.
Create a config/redis.js file to set up the Redis connection. Provide your Redis host, port, and password (if necessary) using environment variables loaded with dotenv. Alternatively, you can use the REDIS_URL environment variable with a connection string.
The .gitignore file excludes sensitive information (like .env) and unnecessary files (like node_modules) from your Git repository. This is crucial for security and avoids bloating your project's version history.
Yes, Prisma supports various databases (PostgreSQL, MySQL, SQLite, and more). You'll need to adjust the datasource provider and connection string in your Prisma schema and .env file accordingly.
Use the concurrently package and the "dev" script defined in package.json. This script simultaneously runs both the API server with nodemon (auto-restarts) and the worker process with nodemon.
Build a Bulk SMS System with MessageBird, Node.js, and Fastify
Learn how to build a production-ready bulk SMS messaging system using MessageBird API with Node.js and Fastify. This comprehensive tutorial covers building a scalable SMS broadcast application that handles large message volumes efficiently using asynchronous job queues with BullMQ and Redis. You'll implement MessageBird Node.js SDK integration, create a high-performance Fastify API, and configure background workers for reliable SMS delivery at scale.
This guide provides a complete walkthrough for building a production-ready Node.js application using the Fastify framework to send bulk or broadcast SMS messages via the MessageBird API. You'll cover everything from project setup and core logic to asynchronous processing, error handling, security, and deployment.
You'll learn how to create a system that efficiently handles sending large volumes of SMS messages without blocking your main application thread, incorporating best practices for reliability and scalability.
Technologies Used:
messagebird
): Official Node.js client that simplifies interaction with the MessageBird REST API.env
fileSystem Architecture:
Here's a high-level overview of how the components interact:
What You'll Build:
By the end of this guide, you will have:
Prerequisites:
originator
1. Setting Up Your Node.js Bulk SMS Project
Initialize your Node.js project and install the necessary dependencies for building a MessageBird SMS integration with Fastify.
1.1 Create Project Directory and Initialize
Open your terminal and create a new directory for your project, then navigate into it.
Initialize the Node.js project using npm (or yarn):
This creates a
package.json
file.1.2 Install Dependencies
Install Fastify, the MessageBird SDK, BullMQ, Redis client, dotenv, and Prisma (if using database tracking).
fastify
: The web frameworkmessagebird
: The official MessageBird Node.js SDK (formerly referenced as@messagebird/api
in some examples)bullmq
: The job queue libraryioredis
: A robust Redis client needed by BullMQdotenv
: Loads environment variables from a.env
fileprisma
,@prisma/client
,pg
: For database interaction (ORM, client, PostgreSQL driver)nodemon
: Automatically restarts the server during development on file changesconcurrently
: Runs multiple commands concurrently (useful for running the API and worker)1.3 Project Structure
Create the following directory structure within your project root:
1.4 Configure Environment Variables
Create a
.env
file in the project root. This file holds your sensitive credentials and configuration. Never commit this file to version control.Also create a
.env.example
file to show the required variables..env.example
:Copy
.env.example
to.env
and fill in your actual credentials:MESSAGEBIRD_API_KEY
: Your live API access key from the MessageBird dashboard (Developers → API access → Show key)MESSAGEBIRD_ORIGINATOR
: The sender ID for your SMS messages. This can be:+12025550147
)MyCompany
, max 11 characters). Note: Alphanumeric IDs are not supported in all countries (e.g., the US) and cannot receive replies. Check MessageBird's country restrictions. Use a number for broader compatibilityREDIS_HOST
,REDIS_PORT
,REDIS_PASSWORD
/REDIS_URL
: Connection details for your Redis serverDATABASE_URL
: (Optional) Connection string for your PostgreSQL database if using Prisma. Follow the format specified in the Prisma documentation for your specific databaseAPI_PORT
,API_HOST
: Network configuration for the Fastify serverQUEUE_NAME
: A name for the BullMQ job queue1.5 Configure
.gitignore
Create a
.gitignore
file in the root to prevent sensitive files and unnecessary folders from being committed:.gitignore
:1.6 (Optional) Initialize Prisma
If you're using the database for tracking, initialize Prisma:
This creates the
prisma/
directory and aschema.prisma
file. Updateprisma/schema.prisma
(covered later in Section 6).1.7 Configure
package.json
ScriptsAdd scripts to your
package.json
for easier development and execution:package.json
(add/update thescripts
section):start:api
/start:worker
: Run the API server and worker in productiondev:api
/dev:worker
: Run the API server and worker usingnodemon
for development (auto-restarts on changes)dev
: Runs both the API and worker concurrently for development usingconcurrently
db:migrate
,db:studio
: (Optional) Prisma commands for database migrations and GUIYour basic project structure and configuration are now complete.
2. Implementing MessageBird API Integration and Job Queue
Implement the core logic for sending messages via MessageBird and set up the asynchronous queue.
2.1 Configure MessageBird Service for SMS Sending
Create a service file to encapsulate MessageBird interactions.
src/services/messagebirdService.js
:messagebird
package. Includes error handling for missing keys or initialization failuressendSms
function:recipient
andbody
as argumentsparams
object required bymessagebirdClient.messages.create
Promise
to handle the callback-based MessageBird SDK APINote on Bulk Sending: For sending to multiple recipients efficiently, MessageBird also provides a Batch API that allows sending different messages to up to 50 recipients per request. This can be more efficient than individual calls for very large batches.
2.2 Configure Redis and BullMQ for Asynchronous SMS Processing
Set up the connection to Redis and define the BullMQ queue.
src/config/redis.js
:.env
REDIS_URL
src/jobs/smsQueue.js
:Queue
instance, connecting it to Redis via the shared connectiondefaultJobOptions
: Configures crucial settings:attempts
,backoff
,removeOnComplete
/removeOnFail
addSmsJob
function: Adds a new job to the queue with recipient and body data2.3 Create the Background Worker for SMS Job Processing
This process listens to the queue and executes the jobs.
src/worker.js
:Worker
instance listening to the queueprocessSmsJob
Function: The core job execution logic, callingsendSms
. Handles errors and re-throws them for BullMQ retries. Includes optional Prisma integration points3. Building the Fastify REST API for Bulk SMS
Create the Fastify server and the API endpoint to receive bulk SMS requests.
src/api.js
:bulkSmsSchema
): Defines request body structure, including updated E.164 regex (^\\+[1-9]\\d{1,14}$
). Defines202 Accepted
response schema/send-bulk
Route: Validates input, iterates recipients, callsaddSmsJob
for each, handles queuing errors, returns202 Accepted
. Includes optional Prisma integration points/health
Route: Basic health check endpoint4. MessageBird API Integration Guide
The core integration with MessageBird happens within the
src/services/messagebirdService.js
file, which was created and updated in Section 2.1.Key Integration Points Recap:
messagebird(process.env.MESSAGEBIRD_API_KEY)
securely initializes the SDK using the API key from environment variables and themessagebird
package (the official Node.js client)messagebirdClient.messages.create(params, callback)
is the method used to send individual SMS messages. ThesendSms
function wraps this logicMESSAGEBIRD_ORIGINATOR
environment variable determines the sender ID.env
fileObtaining API Credentials (Dashboard Navigation):
MESSAGEBIRD_API_KEY
in your.env
fileEnvironment Variable Summary:
MESSAGEBIRD_API_KEY
:live_xxxxxxxxxxxxxxxxxxxxxxx
)MESSAGEBIRD_ORIGINATOR
:+12025550147
) or an alphanumeric string (max 11 characters, e.g.,MyCompany
).env
file