Developer Quick-Start: A step-by-step guide to creating a production-ready appointment reminder system using Node.js, Express, and the Infobip SMS API. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.
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:
- Receive requests to schedule an SMS reminder via a REST API endpoint.
- Store reminder details (phone number, message, scheduled time).
- Reliably check for due reminders at regular intervals.
- Send the scheduled SMS messages using the Infobip API when they become due.
- Provide basic mechanisms for logging, error handling, and security.
Problem Solved: Automating time-sensitive SMS notifications, reducing manual effort, and improving user engagement or adherence (e.g., reducing missed appointments).
Technologies Used:
- Node.js: Asynchronous JavaScript runtime for building the backend server.
- Express: Minimalist web framework for Node.js, used to create the REST API.
- Infobip Node.js SDK: Simplifies interaction with the Infobip SMS API.
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.- (Optional but Recommended) SQLite: A simple file-based SQL database for persisting reminders (can be swapped for other databases).
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:
- Node.js and npm (or yarn) installed. Install Node.js
- An active Infobip account. Sign up for Infobip
- Basic understanding of JavaScript, Node.js, REST APIs, and asynchronous programming.
- A text editor or IDE (e.g., VS Code).
- A tool for testing APIs (e.g., Postman or 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.
mkdir node-infobip-scheduler
cd node-infobip-scheduler
- Initialize npm: Initialize the project using npm. The
-yflag accepts default settings.
npm init -y
This creates a package.json file.
- Enable ES Modules: Since the code examples use
import/exportsyntax (ES Modules), add the following line to yourpackage.jsonfile:
{
"type": "module",
}
- Install Dependencies: Install Express, the Infobip SDK,
node-cron,dotenv,uuid, andexpress-validator.
npm install express @infobip-api/sdk node-cron dotenv uuid express-validator
- Install Development Dependencies (Optional but Recommended): Install
nodemonfor automatic server restarts during development.
npm install --save-dev nodemon
- (Optional) Install Database Driver: If using SQLite for persistence (recommended over in-memory for reliability):
npm install sqlite3 sqlite
- Create Project Structure: Set up a basic folder structure for better organization:
node-infobip-scheduler/
βββ src/
β βββ config/
β β βββ infobip.js # Infobip SDK configuration
β βββ controllers/
β β βββ reminderController.js # API request handlers
β βββ routes/
β β βββ reminderRoutes.js # API routes definition
β βββ services/
β β βββ reminderService.js # Core logic for managing reminders
β β βββ schedulerService.js # Logic for cron job scheduling
β βββ middleware/
β β βββ validator.js # Request validation rules
β βββ db/ # Database related files (optional)
β βββ database.js # DB connection/setup
β βββ schema.sql # DB schema definition
βββ app.js # Express application setup
βββ .env # Environment variables (DO NOT COMMIT)
βββ .gitignore # Specifies files git should ignore
βββ package.json
βββ package-lock.json
- Create
.gitignore: Create a.gitignorefile in the root directory to prevent sensitive files and unnecessary directories from being committed to version control.
# .gitignore
node_modules/
.env
*.log
db/*.sqlite # Or your specific DB file extension
- Create
.envFile: Create a.envfile in the root directory. This file will hold your Infobip credentials and other configuration. Remember to add.envto your.gitignorefile.
ini
PORT=3000
INFOBIP_API_KEY=YOUR_INFOBIP_API_KEY
INFOBIP_BASE_URL=YOUR_INFOBIP_BASE_URL
DATABASE_PATH=./db/reminders.sqlite
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:
- Log in to your Infobip Portal.
- Your Base URL is usually visible on the homepage dashboard after login or in the API documentation section. It's specific to your account/region.
- Navigate to Apps > API Keys (or similar section).
- Click the button to create a new API key (e.g., "New API Key", "Create API Key", or similar text) or use an existing one.
- Copy the generated API Key and your Base URL into your .env file.
- Add npm Scripts: Update the
scriptssection in yourpackage.jsonfor easier starting and development:
{
"type": "module",
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
}
- npm start: Runs the application using Node.
- npm run dev: Runs the application using nodemon 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.
import { Infobip, AuthType } from '@infobip-api/sdk';
import dotenv from 'dotenv';
dotenv.config();
if (!process.env.INFOBIP_BASE_URL || !process.env.INFOBIP_API_KEY) {
console.error(""FATAL ERROR: Infobip API Key or Base URL not configured in .env file."");
process.exit(1);
}
const infobipClient = new Infobip({
baseUrl: process.env.INFOBIP_BASE_URL,
apiKey: process.env.INFOBIP_API_KEY,
authType: AuthType.ApiKey,
});
export default infobipClient;
- We import the necessary parts from the SDK and dotenv.
- We explicitly check for the presence of API Key and Base URL, exiting if they are missing to prevent runtime errors.
- We create and export a configured infobipClient instance.
- Setup Database (Optional - SQLite Example) (
src/db/database.jsandsrc/db/schema.sql): If using SQLite, set up the database connection and ensure the table exists.
- Schema Definition (
src/db/schema.sql):
CREATE TABLE IF NOT EXISTS reminders (
id TEXT PRIMARY KEY,
phoneNumber TEXT NOT NULL,
message TEXT NOT NULL,
scheduleTime TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
createdAt TEXT DEFAULT CURRENT_TIMESTAMP,
updatedAt TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TRIGGER IF NOT EXISTS update_reminders_updatedAt
AFTER UPDATE ON reminders FOR EACH ROW
BEGIN
UPDATE reminders SET updatedAt = CURRENT_TIMESTAMP WHERE id = OLD.id;
END;
CREATE INDEX IF NOT EXISTS idx_reminders_pending_scheduleTime
ON reminders (status, scheduleTime)
WHERE status = 'pending';
- Database Setup (
src/db/database.js): (Note: This code uses the ES Module pattern to get the directory path, replacing the CommonJS__dirname)
import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
import fs from 'fs';
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
dotenv.config();
const defaultDbPath = path.resolve(__dirname, 'reminders.sqlite');
const dbPath = process.env.DATABASE_PATH || defaultDbPath;
const dbDir = path.dirname(dbPath);
if (!fs.existsSync(dbDir)) {
try {
fs.mkdirSync(dbDir, { recursive: true });
console.log(`Database directory created at: ${dbDir}`);
} catch (error) {
console.error(`Error creating database directory at ${dbDir}:`, error);
process.exit(1);
}
}
let db;
async function initializeDatabase() {
if (db) return db;
try {
db = await open({
filename: dbPath,
driver: sqlite3.Database
});
console.log('Connected to the SQLite database.');
const schemaPath = path.resolve(__dirname, 'schema.sql');
const schemaSql = fs.readFileSync(schemaPath, 'utf8');
await db.exec(schemaSql);
console.log('Database schema ensured.');
return db;
} catch (error) {
console.error('Error initializing SQLite database:', error);
process.exit(1);
}
}
async function getDb() {
if (!db) {
await initializeDatabase();
}
return db;
}
export { getDb, initializeDatabase };
- Uses the import.meta.url pattern to correctly determine the directory path in ES Modules.
- Sets up a connection using the sqlite library (which provides async/await support over sqlite3).
- Reads the schema.sql file and executes it to ensure the reminders table and indexes exist on startup.
- Handles potential errors during initialization.
- Reminder Service (
src/services/reminderService.js): This service handles the business logic for creating, retrieving, and updating reminders.
import { v4 as uuidv4 } from 'uuid';
import { getDb } from '../db/database.js';
import infobipClient from '../config/infobip.js';
async function addReminder(phoneNumber, message, scheduleTime) {
const db = await getDb();
const id = uuidv4();
const isoScheduleTime = new Date(scheduleTime).toISOString();
if (isNaN(new Date(isoScheduleTime).getTime())) {
throw new Error('Invalid scheduleTime format. Please use ISO 8601 format.');
}
if (new Date(isoScheduleTime) <= new Date()) {
throw new Error('Schedule time must be in the future.');
}
try {
const result = await db.run(
'INSERT INTO reminders (id, phoneNumber, message, scheduleTime) VALUES (?, ?, ?, ?)',
[id, phoneNumber, message, isoScheduleTime]
);
console.log(`Reminder added with ID: ${id}`);
return { id, phoneNumber, message, scheduleTime: isoScheduleTime, status: 'pending' };
} catch (error) {
console.error('Error adding reminder to DB:', error);
throw new Error('Failed to schedule reminder.');
}
}
async function getDueReminders() {
const db = await getDb();
const now = new Date().toISOString();
try {
const reminders = await db.all(
""SELECT * FROM reminders WHERE status = 'pending' AND scheduleTime <= ?"",
[now]
);
return reminders;
} catch (error) {
console.error('Error fetching due reminders:', error);
return [];
}
}
async function updateReminderStatus(id, status, errorInfo = null) {
const db = await getDb();
try {
const updateSql = status === 'failed'
? ""UPDATE reminders SET status = ?, updatedAt = CURRENT_TIMESTAMP WHERE id = ?""
: ""UPDATE reminders SET status = ?, updatedAt = CURRENT_TIMESTAMP WHERE id = ?"";
await db.run(updateSql, [status, id]);
console.log(`Reminder ${id} status updated to: ${status}`);
if (status === 'failed' && errorInfo) {
console.error(`Reminder ${id} failed:`, errorInfo);
}
} catch (error) {
console.error(`Error updating reminder ${id} status to ${status}:`, error);
}
}
async function sendSms(phoneNumber, message) {
console.log(`Attempting to send SMS to ${phoneNumber}`);
try {
const response = await infobipClient.channels.sms.send({
messages: [
{
destinations: [{ to: phoneNumber }],
from: 'InfoSMS',
text: message,
},
],
});
const sentMessageInfo = response.data.messages[0];
console.log(`SMS sent successfully to ${phoneNumber}. Message ID: ${sentMessageInfo?.messageId}, Status: ${sentMessageInfo?.status?.name}`);
return { success: true, response: response.data };
} catch (error) {
console.error(`Error sending SMS via Infobip to ${phoneNumber}:`, error.response?.data || error.message);
const errorDetails = error.response?.data?.requestError?.serviceException || { message: error.message };
return { success: false, error: errorDetails };
}
}
export { addReminder, getDueReminders, updateReminderStatus, sendSms };
- Provides functions to interact with the data store (either SQLite or in-memory). Includes clear comments guiding the user to choose ONE implementation.
- Includes the sendSms function using the configured infobipClient.
- Handles basic validation for schedule time.
- Includes basic error logging for database and Infobip operations.
- Crucially, it stores and compares dates in UTC (using toISOString()).
- Scheduler Service (
src/services/schedulerService.js): This service usesnode-cronto periodically check for and process due reminders.
import cron from 'node-cron';
import { getDueReminders, updateReminderStatus, sendSms } from './reminderService.js';
const cronJob = cron.schedule('* * * * *', async () => {
console.log(`[${new Date().toISOString()}] Running scheduler: Checking for due reminders...`);
try {
const dueReminders = await getDueReminders();
if (dueReminders.length === 0) {
return;
}
console.log(`[${new Date().toISOString()}] Found ${dueReminders.length} due reminders. Processing...`);
for (const reminder of dueReminders) {
console.log(`Processing reminder ID: ${reminder.id} for ${reminder.phoneNumber}`);
const sendResult = await sendSms(reminder.phoneNumber, reminder.message);
if (sendResult.success) {
await updateReminderStatus(reminder.id, 'sent');
} else {
const errorMessage = sendResult.error?.message || JSON.stringify(sendResult.error);
console.error(`Failed to send reminder ID: ${reminder.id}. Error: ${errorMessage}`);
await updateReminderStatus(reminder.id, 'failed', errorMessage);
}
}
console.log(`[${new Date().toISOString()}] Finished processing batch of ${dueReminders.length} reminders.`);
} catch (error) {
console.error(`[${new Date().toISOString()}] CRITICAL ERROR in scheduler run:`, error);
}
}, {
scheduled: false
});
function startScheduler() {
console.log('Starting scheduler service...');
cronJob.start();
}
function stopScheduler() {
console.log('Stopping scheduler service...');
cronJob.stop();
}
export { startScheduler, stopScheduler };
- Imports node-cron and the necessary functions from reminderService.
- Defines a cron job (cronJob) that runs every minute (\* \* \* \* \*). You can adjust this frequency based on your needs (e.g., \*/5 \* \* \* \* for every 5 minutes).
- The job fetches due reminders, iterates through them, attempts to send the SMS, and updates the status accordingly ('sent' or 'failed').
- Includes basic logging for scheduler activity and errors.
- Exports startScheduler and stopScheduler 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.
import { body, validationResult } from 'express-validator';
const validateReminderRequest = [
body('phoneNumber')
.trim()
.notEmpty().withMessage('Phone number is required.')
.matches(/^\+?[1-9]\d{1,14}$/).withMessage('Invalid phone number format. Use E.164 format (e.g., +14155552671).'),
body('message')
.trim()
.notEmpty().withMessage('Message is required.')
.isLength({ min: 1, max: 1600 }).withMessage('Message length must be between 1 and 1600 characters.'),
body('scheduleTime')
.notEmpty().withMessage('Schedule time is required.')
.isISO8601({ strict: true, require_tld: false }).withMessage('Schedule time must be a valid ISO 8601 date string (e.g., 2024-12-31T10:00:00Z or 2024-12-31T10:00:00+01:00).')
.custom((value) => {
if (new Date(value) <= new Date()) {
throw new Error('Schedule time must be in the future.');
}
return true;
}),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const formattedErrors = errors.array().map(err => ({
field: err.param,
message: err.msg,
value: err.value,
}));
return res.status(400).json({ errors: formattedErrors });
}
next();
}
];
export { validateReminderRequest };
- Uses body() to specify rules for phoneNumber, message, and scheduleTime.
- Includes a note about the simplified phone number regex.
- Includes checks for emptiness, format (E.164 for phone, ISO 8601 for date), length, and ensures the date is in the future.
- The final middleware function checks validationResult and returns a 400 error with details if validation fails.
- Reminder Controller (
src/controllers/reminderController.js): Handle the logic for the API endpoint.
import { addReminder } from '../services/reminderService.js';
const scheduleReminder = async (req, res, next) => {
const { phoneNumber, message, scheduleTime } = req.body;
try {
const newReminder = await addReminder(phoneNumber, message, scheduleTime);
res.status(201).json({
message: 'Reminder scheduled successfully.',
reminder: {
id: newReminder.id,
phoneNumber: newReminder.phoneNumber,
message: newReminder.message,
scheduleTime: newReminder.scheduleTime,
status: newReminder.status,
}
});
} catch (error) {
console.error('Error in scheduleReminder controller:', error);
next(error);
}
};
export { scheduleReminder };
- Imports the addReminder function.
- Extracts validated data from req.body.
- Calls the service function to create the reminder.
- Responds with a 201 status code and the created reminder's details on success, or passes errors to the global handler (or sends 500).
- Reminder Routes (
src/routes/reminderRoutes.js): Define the API routes and associate them with controllers and middleware.
import express from 'express';
import { scheduleReminder } from '../controllers/reminderController.js';
import { validateReminderRequest } from '../middleware/validator.js';
const router = express.Router();
router.post('/', validateReminderRequest, scheduleReminder);
export default router;
- Creates an Express router instance.
- Defines a POST route at /.
- Applies the validateReminderRequest middleware first, then the scheduleReminder controller.
- Includes a commented-out placeholder for authentication middleware.
- Express App Setup (
src/app.js): Configure the main Express application, load middleware, routes, and start the server and scheduler.
import express from 'express';
import dotenv from 'dotenv';
import reminderRoutes from './routes/reminderRoutes.js';
import { startScheduler, stopScheduler } from './services/schedulerService.js';
import { getDb, initializeDatabase } from './db/database.js';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl} ${res.statusCode} ${duration}ms`);
});
next();
});
app.get('/health', (req, res) => {
res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() });
});
app.use('/api/reminders', reminderRoutes);
app.use((req, res, next) => {
res.status(404).json({ message: 'Not Found' });
});
app.use((err, req, res, next) => {
console.error("Unhandled Error:", err.stack || err);
const isDevelopment = process.env.NODE_ENV === 'development';
res.status(err.status || 500).json({
message: err.message || 'Internal Server Error',
stack: isDevelopment ? err.stack : undefined,
});
});
let server;
async function startServer() {
try {
const usingDb = process.env.DATABASE_PATH || fs.existsSync(path.resolve(dirname(fileURLToPath(import.meta.url)), 'db', 'reminders.sqlite'));
if (usingDb) {
await initializeDatabase();
console.log('Database initialized successfully.');
} else {
console.log('Running without database persistence (using in-memory store).');
}
startScheduler();
server = app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
console.log(`API endpoint available at http://localhost:${PORT}/api/reminders`);
console.log(`Health check available at http://localhost:${PORT}/health`);
});
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
} catch (error) {
console.error('Failed to start the application:', error);
process.exit(1);
}
}
function gracefulShutdown() {
console.log('Received shutdown signal. Closing server and scheduler...');
stopScheduler();
if (server) {
server.close(async () => {
console.log('HTTP server closed.');
try {
const db = await getDb();
if (db && typeof db.close === 'function') {
await db.close();
console.log('Database connection closed.');
}
} catch (dbError) {
console.error('Error closing database connection:', dbError);
} finally {
console.log('Shutdown complete.');
process.exit(0);
}
});
} else {
console.log('No active server to close.');
process.exit(0);
}
setTimeout(() => {
console.error('Could not close connections in time, forcing shutdown.');
process.exit(1);
}, 10000);
}
startServer();
Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)
If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.
curl -X POST https://api.sendsmsnokyc.com/messages \
-H "x-api-key: $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": ["+14155551234"],
"channel": ["sms"],
"body": "Your verification code is 482910"
}'
- Instant onboarding: No KYC paperwork or sales queues β grab an API key and fund with crypto (BTC/USDT) or card.
- Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
- Transparent global pricing: Compare exact per-country termination rates on our live pricing page.
Ship Global SMS in One API Call
Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.
Explore SMSRoute Developers β