Frequently Asked Questions
The Infobip Node.js SDK (@infobip-api/sdk) is initialized using your Infobip Base URL and API Key. This enables the application to communicate with the Infobip platform and seamlessly send SMS messages.
Build a robust SMS reminder application using Node.js, Express, and Infobip by following a step-by-step guide covering project setup, core features, error handling, security, deployment, and testing. This will create a system capable of scheduling and sending SMS reminders based on user-defined times, leveraging the power of Node.js and Infobip's SMS API.
Node-cron is a task scheduler for Node.js, used to trigger reminder checks periodically. It allows the system to automatically check for due reminders at specified intervals and initiate the SMS sending process.
Prisma, a next-generation ORM, is used with PostgreSQL for data persistence. This combination offers efficient database interactions for storing and retrieving reminder data in a robust and reliable manner, enhancing the system's overall performance.
You need Node.js (v18 or later), npm, access to PostgreSQL, an Infobip account, and basic knowledge of Node.js, Express, APIs, and databases. Docker is also recommended for containerized deployment.
The application uses Express to build an API that allows users to schedule SMS reminders for specific dates and times. These reminders are reliably sent using Infobip's SMS API, ensuring timely delivery of messages.
It automates reminder notifications for events like appointments and deadlines. The system provides a reliable, scheduled SMS delivery mechanism, and its decoupled architecture integrates into larger applications.
A client interacts with the Express API, which communicates with a PostgreSQL database for storing and retrieving data. A node-cron scheduler checks for due reminders, triggering the Infobip API via the SDK to send SMS messages to end-users.
Express-rate-limit is employed for basic rate limiting, a crucial security measure that protects your application from abuse by limiting the number of requests a client can make within a specific timeframe. Implementing rate limiting is highly recommended, especially for production environments.
Reminder times (sendAt
) are stored in UTC in the database to avoid ambiguities. The application and the node-cron scheduler are also configured to work in UTC, ensuring consistent and accurate scheduling regardless of user location.
A free Infobip trial account is sufficient for initial testing and development. However, it may have limitations on message volume and features. For production deployments, consider upgrading to a paid account for greater capacity and support.
Express-validator serves as middleware for request data validation, ensuring that the data received by the API conforms to specified criteria (e.g., correct phone number format, message length). This helps improve the reliability and security of the application by preventing unexpected data-related issues.
Reminder data is stored in a PostgreSQL database using a Reminder
model defined in the Prisma schema. This model includes fields for the recipient, message content, scheduled time, and status, providing a structured way to manage reminder information.
Storing the sendAt
timestamp in UTC prevents time zone-related issues, ensuring that reminders are sent at the correct time regardless of the user's or server's geographic location. This is a best practice for any scheduled task system.
The scheduler includes error handling mechanisms to catch and manage exceptions during the reminder processing loop. This helps prevent the entire scheduler from crashing due to isolated errors and ensures the continued operation of the system.
Build a Node.js SMS Reminder System with Express and Infobip
This guide provides a step-by-step walkthrough for building a production-ready SMS reminder application using Node.js, Express, Infobip for sending SMS,
node-cron
for scheduling, and Prisma with PostgreSQL for data persistence.We'll cover everything from project setup and core feature implementation to error handling, security, deployment, and testing. By the end, you'll have a robust system capable of scheduling and sending SMS reminders based on user-defined times.
Project Overview and Goals
What We're Building:
An API-driven application that allows users (or other systems) to schedule SMS reminders to be sent at specific future dates and times. The system will reliably send these messages using Infobip's SMS API.
Problems Solved:
Technologies Used:
@infobip-api/sdk
): Cloud communications platform for sending SMS messages. We use the official SDK for easier integration.node-cron
: Task scheduler for Node.js, used to trigger reminder checks periodically.dotenv
: Module to load environment variables from a.env
file.express-validator
: Middleware for request data validation.winston
: A versatile logging library.express-rate-limit
: Basic rate limiting middleware for Express.System Architecture:
Prerequisites:
Final Outcome:
A running Node.js application with API endpoints to schedule_ list_ and cancel SMS reminders. A background scheduler will periodically check for due reminders and send them via Infobip.
1. Setting up the Project
Let's initialize our project_ install dependencies_ and set up the basic structure.
1.1 Create Project Directory
Open your terminal and create a new directory for the project.
1.2 Initialize Node.js Project
This creates a
package.json
file.1.3 Install Dependencies
1.4 Install Development Dependencies
prisma
: The Prisma CLI for database migrations and client generation.nodemon
: Utility that automatically restarts the Node application when file changes are detected during development.1.5 Configure
package.json
ScriptsAdd the following scripts to your
package.json
for easier development and execution:Note: Replace
"test"
script with your actual test command (e.g._"jest"
if using Jest). Ensure dependency versions are appropriate for your project.1.6 Initialize Prisma
Set up Prisma and connect it to your PostgreSQL database.
This creates:
prisma
directory with aschema.prisma
file..env
file (if it doesn't exist) with aDATABASE_URL
placeholder.1.7 Configure Environment Variables (
.env
)Open the
.env
file and add your configuration. Replace placeholders with your actual credentials. Do not commit this file to version control.Obtaining Infobip Credentials:
xxxxxx.api.infobip.com
.1.8 Define Project Structure
Create the following directory structure within your project root:
Create the necessary directories:
Add
node_modules
,.env
, and potentially build output directories to your.gitignore
file.Why this structure? Separating concerns (config, routes, controllers, services, middleware) makes the application more organized, maintainable, and testable as it grows.
2. Creating a Database Schema and Data Layer
We need a way to store the reminders. We'll use Prisma and PostgreSQL.
2.1 Define the Prisma Schema
Open
prisma/schema.prisma
and define theReminder
model.recipient
: Store phone numbers consistently, preferably in E.164 format (e.g.,+14155552671
).sendAt
: Crucially, store this timestamp in UTC to avoid time zone ambiguities. We'll handle conversions at the application layer if needed.status
: Tracks the state of the reminder. Consider adding more granular statuses if implementing retries or delivery reports.@@index([sendAt, status])
: Creates a database index onsendAt
andstatus
, which is vital for the scheduler to efficiently query pending reminders due for sending.2.2 Create and Apply Database Migration
Run the Prisma migrate command to create the SQL migration file and apply it to your database. Make sure your database server is running and accessible via the
DATABASE_URL
in.env
.This command will:
migrations
folder insideprisma
.Reminder
table.DATABASE_URL
.npx prisma generate
).2.3 Initialize Prisma Client
Create a singleton instance of the Prisma client to be used throughout the application.
2.4 Create the Reminder Service
This service will contain the business logic for interacting with the
Reminder
model in the database.3. Integrating with Infobip for SMS Sending
Now, let's set up the Infobip SDK and create a service to handle sending SMS messages.
3.1 Configure Environment Variables Loader
Create a utility to load and validate essential environment variables.
3.2 Initialize Infobip Client
Set up the Infobip SDK instance.
3.3 Create the SMS Service
This service encapsulates the logic for sending SMS messages via the Infobip SDK.
Key points:
@infobip-api/sdk
for interaction.sendSms
function takes recipient, message, and an optional sender ID. Sender ID regulations vary by country – consult Infobip documentation. Using a registered number might be required.catch
) and API-reported errors within a successful (2xx) response. More detailed error message extraction is attempted.messageResult.status.groupId
. According to Infobip docs, group ID 1 (PENDING) generally means the message was accepted for processing. Other group IDs (2-REJECTED, 4-FAILED, 5-EXPIRED) indicate issues. Refer to Infobip Status Codes for details.4. Implementing Core Functionality: The Scheduler
This is the heart of the reminder system. We'll use
node-cron
to periodically check for due reminders and trigger the sending process.4.1 Create the Scheduler Service
Key aspects:
node-cron
: Used to schedule theprocessDueReminders
function based on theSCHEDULER_CRON_PATTERN
from the.env
file.timezone: ""Etc/UTC""
). This is critical for consistency, as remindersendAt
times are stored in UTC.isRunning
): A simple flag prevents the job from running multiple times concurrently if a previous run takes longer than the interval. For high-load scenarios, a more robust locking mechanism (e.g., using Redis or database advisory locks) might be needed.FAILED
. Note: This version lacks sophisticated retry logic.findDueReminders
fetches reminders in batches (take: 100
) to avoid loading too many into memory.server.js
which callsstopScheduler
.5. Building the API Layer with Express
We need endpoints for external systems or a frontend to interact with our reminder service.
5.1 Configure Logging
Set up Winston for structured logging.