Frequently Asked Questions
This tutorial provides a comprehensive guide to building an SMS reminder system using Node.js, Express, and the Infobip API. You'll learn how to set up the project, handle API requests, schedule reminders, and send SMS notifications reliably. The system uses node-cron for scheduling and offers options for persistent storage with SQLite or an in-memory store for simplicity.
The Infobip SMS API is the core communication component of the reminder system. It's used to send the actual SMS messages to users at the scheduled time. The Infobip Node.js SDK simplifies interaction with the API, handling authentication and requests.
Node-cron is a task scheduler for Node.js that allows you to define tasks to run at specific intervals, similar to cron jobs. This is essential for checking the database or in-memory store periodically for reminders that are due to be sent.
SQLite is recommended for production environments or any scenario where data persistence is required. If the server restarts, reminders stored in SQLite will be preserved, unlike the in-memory option where data is lost on restart.
While the tutorial uses SQLite as an example for persistent storage, you can adapt it to other databases. The core logic for interacting with the database is encapsulated in the reminderService.js
file, allowing for flexibility in database choice.
You'll need an active Infobip account. The API key and base URL can be found in your Infobip portal. Create a .env
file in your project's root directory and store these credentials there. Ensure the .env
file is added to your .gitignore
to prevent it from being committed to version control.
Express-validator is used to validate incoming API requests, ensuring that required fields like phone number, message, and schedule time are present and in the correct format. This adds robustness and security to the system.
The tutorial provides a basic regex for E.164 phone number format validation. For more comprehensive validation, consider using a specialized library like libphonenumber-js
which can handle various international phone number formats and validation rules.
You should have Node.js and npm (or yarn) installed. An active Infobip account and API key are required. A basic understanding of REST APIs, asynchronous programming, and JavaScript is also recommended.
The project demonstrates basic error handling, including checking for configuration errors, catching database issues, logging Infobip API errors, and using a global error handler in Express to catch and format errors for appropriate responses.
Once the server is running, you can use tools like Postman or curl
to send test requests to the API endpoint (/api/reminders
). These tools allow you to send POST requests with the required data (phone number, message, and schedule time) and examine the responses.
After setting up the project, use npm start
to run the application in production mode. For development, use npm run dev
which automatically restarts the server whenever you make changes to the code. This requires installing nodemon as a development dependency.
The diagram illustrates the flow of data and interactions within the reminder system. It visually represents how client requests flow through the API, interact with the services, and eventually send messages via the Infobip API.
The project uses Node.js with Express for building the backend API and handling requests. Infobip's SMS API and Node.js SDK handle messaging, while node-cron schedules tasks. SQLite provides optional persistent storage, and express-validator manages request validation.
Storing schedule times in UTC (using toISOString()) ensures consistency and avoids issues related to time zones. This is especially important in reminder systems to ensure that messages are sent at the correct time, regardless of the server's location or the user's time zone.
This guide provides a step-by-step walkthrough for building a production-ready appointment reminder system using Node.js, Express, and the Infobip SMS API. We'll cover everything from project setup and core scheduling logic to robust error handling, security considerations, and deployment.
By the end of this tutorial, you will have a functional application capable of accepting reminder requests via an API, scheduling them, and reliably sending SMS notifications at the specified time using Infobip. This solves the common business need for automated, time-sensitive communication like appointment confirmations, payment due dates, or event reminders.
Last Updated: October 26, 2023
Project Overview and Goals
Goal: To create a backend service that can:
Problem Solved: Automating time-sensitive SMS notifications, reducing manual effort, and improving user engagement or adherence (e.g., reducing missed appointments).
Technologies Used:
node-cron
: A simple cron-like job scheduler for Node.js, used to trigger checks for due reminders.dotenv
: Loads environment variables from a.env
file.uuid
: Generates unique IDs for reminders.express-validator
: Middleware for request validation.System Architecture:
Placeholder: Insert a system architecture diagram image (e.g., PNG or SVG) here. The diagram should illustrate the flow from Client App -> Node.js/Express API -> Reminder Service -> Database, with the Reminder Service interacting with
node-cron
and the Infobip Service, which in turn calls the Infobip API.Prerequisites:
curl
).Final Outcome: A running Node.js application with an API endpoint to schedule SMS reminders, which are then automatically sent at the correct time via Infobip.
1. Setting up the Project
Let's initialize our Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal and create a new directory for the project, then navigate into it.
Initialize npm: Initialize the project using npm. The
-y
flag accepts default settings.This creates a
package.json
file.Enable ES Modules: Since the code examples use
import
/export
syntax (ES Modules), add the following line to yourpackage.json
file:Install Dependencies: Install Express, the Infobip SDK,
node-cron
,dotenv
,uuid
, andexpress-validator
.Install Development Dependencies (Optional but Recommended): Install
nodemon
for automatic server restarts during development.(Optional) Install Database Driver: If using SQLite for persistence (recommended over in-memory for reliability):
Create Project Structure: Set up a basic folder structure for better organization:
Create
.gitignore
: Create a.gitignore
file in the root directory to prevent sensitive files and unnecessary directories from being committed to version control.Create
.env
File: Create a.env
file in the root directory. This file will hold your Infobip credentials and other configuration. Remember to add.env
to your.gitignore
file.PORT
: The port your Express server will listen on.INFOBIP_API_KEY
: Your secret API key from Infobip.INFOBIP_BASE_URL
: Your unique base URL provided by Infobip (check your dashboard).DATABASE_PATH
: Path to the SQLite database file.How to find Infobip API Key and Base URL:
.env
file.Add npm Scripts: Update the
scripts
section in yourpackage.json
for easier starting and development:npm start
: Runs the application using Node.npm run dev
: Runs the application usingnodemon
for auto-restarts.2. Implementing Core Functionality
Now, let's implement the core logic: configuring Infobip, managing reminders, and setting up the scheduler.
Configure Infobip SDK (
src/config/infobip.js
): Create a file to initialize the Infobip client instance.dotenv
.infobipClient
instance.Setup Database (Optional - SQLite Example) (
src/db/database.js
andsrc/db/schema.sql
): If using SQLite, set up the database connection and ensure the table exists.Schema Definition (
src/db/schema.sql
):Database Setup (
src/db/database.js
): (Note: This code uses the ES Module pattern to get the directory path, replacing the CommonJS__dirname
)import.meta.url
pattern to correctly determine the directory path in ES Modules.sqlite
library (which provides async/await support oversqlite3
).schema.sql
file and executes it to ensure thereminders
table and indexes exist on startup.Reminder Service (
src/services/reminderService.js
): This service handles the business logic for creating, retrieving, and updating reminders.sendSms
function using the configuredinfobipClient
.toISOString()
).Scheduler Service (
src/services/schedulerService.js
): This service usesnode-cron
to periodically check for and process due reminders.node-cron
and the necessary functions fromreminderService
.cronJob
) that runs every minute (* * * * *
). You can adjust this frequency based on your needs (e.g.,*/5 * * * *
for every 5 minutes).startScheduler
andstopScheduler
functions to control the job lifecycle.3. Building the API Layer
We'll now create the Express API endpoint to accept requests for scheduling reminders.
Request Validation Middleware (
src/middleware/validator.js
): Define validation rules usingexpress-validator
.body()
to specify rules forphoneNumber
,message
, andscheduleTime
.validationResult
and returns a 400 error with details if validation fails.Reminder Controller (
src/controllers/reminderController.js
): Handle the logic for the API endpoint.addReminder
function.req.body
.Reminder Routes (
src/routes/reminderRoutes.js
): Define the API routes and associate them with controllers and middleware.POST
route at/
.validateReminderRequest
middleware first, then thescheduleReminder
controller.Express App Setup (
src/app.js
): Configure the main Express application, load middleware, routes, and start the server and scheduler.