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 Node.js Fastify app for bulk SMS messaging with MessageBird
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. We'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 can efficiently handle sending potentially large volumes of SMS messages without blocking your main application thread, incorporating best practices for reliability and scalability.
Technologies Used:
.env
file.System Architecture:
Here’s a high-level overview of how the components interact:
Final Outcome:
By the end of this guide, you will have:
Prerequisites:
originator
.1. Setting up the project
Let's initialize our Node.js project and install the necessary dependencies.
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 the database tracking).
fastify
: The web framework.@messagebird/api
: The official MessageBird Node.js SDK.bullmq
: The job queue library.ioredis
: A robust Redis client needed by BullMQ.dotenv
: Loads environment variables from a.env
file.prisma
,@prisma/client
,pg
: For database interaction (ORM, client, PostgreSQL driver).nodemon
: Automatically restarts the server during development on file changes.concurrently
: 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 will hold 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 chars). 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 compatibility.REDIS_HOST
,REDIS_PORT
,REDIS_PASSWORD
/REDIS_URL
: Connection details for your Redis server.DATABASE_URL
: (Optional) Connection string for your PostgreSQL database if using Prisma. Follow the format specified in the Prisma documentation for your specific database.API_PORT
,API_HOST
: Network configuration for the Fastify server.QUEUE_NAME
: A name for the BullMQ job queue.1.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 production.dev: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 GUI.Your basic project structure and configuration are now complete.
2. Implementing core functionality
Now, let's implement the core logic for sending messages via MessageBird and setting up the asynchronous queue.
2.1 Configure MessageBird Service
Create a service file to encapsulate MessageBird interactions.
src/services/messagebirdService.js
:@messagebird/api
package style. Includes error handling for missing keys or initialization failures.sendSms
function:recipient
andbody
as arguments.params
object required bymessagebird.messages.create
.Promise
to handle the asynchronous nature (assuming the SDK might still use callbacks, or providing compatibility with the original code). Includes comments on how to simplify if the new SDK returns promises directly.2.2 Configure Redis and BullMQ
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 connection.defaultJobOptions
: Configures crucial settings:attempts
,backoff
,removeOnComplete
/removeOnFail
.addSmsJob
function: Adds a new job to the queue with recipient and body data.2.3 Create the Background Worker
This process listens to the queue and executes the jobs.
src/worker.js
:Worker
instance listening to the queue.processSmsJob
Function: The core job execution logic, callingsendSms
. Handles errors and re-throws them for BullMQ retries. Includes optional Prisma integration points.3. Building the Fastify API layer
Let's 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 endpoint.4. Integrating with MessageBird (Covered in Section 2.1)
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:
messagebirdClient(process.env.MESSAGEBIRD_API_KEY)
securely initializes the SDK using the API key from environment variables and the@messagebird/api
package.messagebird.messages.create(params, callback)
(or its promise-based equivalent in the newer SDK) is the method used to send individual SMS messages. ThesendSms
function wraps this logic.MESSAGEBIRD_ORIGINATOR
environment variable determines the sender ID..env
file.Obtaining API Credentials (Dashboard Navigation):
MESSAGEBIRD_API_KEY
in your.env
file.Environment Variable Summary:
MESSAGEBIRD_API_KEY
:live_xxxxxxxxxxxxxxxxxxxxxxx
).MESSAGEBIRD_ORIGINATOR
:+12025550147
) or an alphanumeric string (max 11 chars, e.g.,MyCompany
)..env
file.