Developer Quick-Start: A step-by-step guide to creating an SMS reminder application using Node.js, Express, Infobip, node-cron, Prisma, and PostgreSQL. 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 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:
- Automating reminder notifications (e.g., appointments, deadlines, events).
- Providing a reliable mechanism for scheduled SMS delivery.
- Creating a decoupled service that can be integrated into larger applications.
Technologies Used:
- Node.js: JavaScript runtime for the backend server.
- Express: Web application framework for Node.js, used to build the API.
- Infobip API & Node.js SDK (
@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.- Prisma: Next-generation ORM for Node.js and TypeScript, used for database interactions.
- PostgreSQL: Robust open-source relational database for storing reminder data.
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.- Docker: For containerizing the application for deployment.
System Architecture:
+-----------+ +-----------------+ +-----------------+ +---------+ +---------------+ +-----------+
| Client | ----> | Express API | ---> | Database (PG) | <--- | Scheduler | ---> | Infobip API | ---> | End User |
| (e.g. UI, | | (Node.js) | | (Reminders) | | (node-cron) | | (via SDK) | | (via SMS) |
| script) | <---- | | +-----------------+ +-----------+ +---------------+ +-----------+
+-----------+ +-----------------+
(Schedule (Stores/Retrieves (Checks for due
Reminder) Reminder Data) reminders &
triggers sending)
Prerequisites:
- Node.js (v18 or later recommended) and npm installed.
- Access to a PostgreSQL database (local or cloud-based).
- An Infobip account (a free trial account works, but may have limitations).
- Basic familiarity with Node.js, Express, APIs, and databases.
- Docker installed (for deployment section).
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.
mkdir node-sms-reminders
cd node-sms-reminders
1.2 Initialize Node.js Project
npm init -y
This creates a package.json file.
1.3 Install Dependencies
npm install express dotenv @infobip-api/sdk node-cron @prisma/client pg express-validator winston express-rate-limit
1.4 Install Development Dependencies
npm install -D prisma nodemon
- 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 Scripts
Add the following scripts to your package.json for easier development and execution:
{
"name": "node-sms-reminders",
"version": "1.0.0",
"description": "SMS Reminder Application",
"main": "src/server.js",
"type": "module",
"scripts": {
"start": "node src/server.js",
"dev": "nodemon src/server.js",
"prisma:migrate": "prisma migrate dev",
"prisma:generate": "prisma generate",
"prisma:studio": "prisma studio",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"@infobip-api/sdk": "^2.0.0",
"@prisma/client": "^5.0.0",
"dotenv": "^16.0.0",
"express": "^4.18.0",
"express-rate-limit": "^7.0.0",
"express-validator": "^7.0.0",
"node-cron": "^3.0.0",
"pg": "^8.10.0",
"winston": "^3.9.0"
},
"devDependencies": {
"nodemon": "^3.0.0",
"prisma": "^5.0.0"
}
}
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.
npx prisma init --datasource-provider postgresql
This creates:
- A prisma directory with a schema.prisma file.
- A .env file (if it doesn't exist) with a DATABASE\_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.
.env
# .env
# Database Connection
# Example: postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public
DATABASE_URL="postgresql://postgres:yourpassword@localhost:5432/sms_reminders?schema=public"
# Infobip API Credentials
# Get these from your Infobip account dashboard
INFOBIP_BASE_URL="YOUR_INFOBIP_BASE_URL" # e.g., xyzabc.api.infobip.com
INFOBIP_API_KEY="YOUR_INFOBIP_API_KEY"
# Application Settings
PORT=3000
NODE_ENV=development # Set to 'production' in deployment
# Security
# Generate a strong random string for API key authentication
# LEAVE EMPTY ONLY FOR LOCAL DEVELOPMENT WHERE AUTH IS INTENTIONALLY SKIPPED (NOT RECOMMENDED FOR PROD)
API_SECRET_KEY="YOUR_STRONG_SECRET_API_KEY_FOR_INTERNAL_AUTH"
# Scheduler Settings (Cron pattern: second minute hour day-of-month month day-of-week)
# Check every minute: '* * * * *'
# Check every 5 minutes: '*/5 * * * *'
SCHEDULER_CRON_PATTERN="* * * * *"
# Logging Level (optional, defaults to 'info')
# LOG_LEVEL=debug
Obtaining Infobip Credentials:
- Log in to your Infobip Account.
- Your Base URL is typically shown on the homepage after login, or navigate to API > API Keys Management. It looks like xxxxxx.api.infobip.com.
- Navigate to API > API Keys Management.
- Click "New API Key" or use an existing one.
- Copy the API Key value.
- Important: Ensure your API key has permissions for SMS messaging.
1.8 Define Project Structure
Create the following directory structure within your project root:
node-sms-reminders/
βββ prisma/
β βββ schema.prisma
β βββ migrations/
βββ src/
β βββ config/
β β βββ index.js # Load and export environment variables
β β βββ logger.js # Winston logger configuration
β β βββ infobip.js # Infobip client initialization
β β βββ prisma.js # Prisma client instance
β βββ controllers/
β β βββ reminderController.js # Handles API request logic
β βββ middleware/
β β βββ authMiddleware.js # API key authentication
β β βββ errorMiddleware.js # Global error handler
β β βββ validationMiddleware.js # Request validation rules
β βββ routes/
β β βββ reminderRoutes.js # Defines API routes for reminders
β βββ services/
β β βββ reminderService.js # Business logic for reminders (DB interaction)
β β βββ schedulerService.js # Logic for the cron scheduler
β β βββ smsService.js # Logic for sending SMS via Infobip
β βββ utils/
β β βββ timeUtils.js # Time zone handling utilities (optional but recommended)
β βββ server.js # Main application entry point (Express setup)
βββ .env
βββ .gitignore
βββ package.json
βββ package-lock.json
# Optional: jest.config.js, .eslintrc.json, etc.
Create the necessary directories:
mkdir -p src/config src/controllers src/middleware src/routes src/services src/utils
Add node_modules, .env, and potentially build output directories to your
.gitignore file.
# .gitignore
node_modules
.env
dist
coverage
*.log
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 the Reminder model.
Prisma
// prisma/schema.prisma
generator client {
provider = ""prisma-client-js""
}
datasource db {
provider = ""postgresql""
url = env(""DATABASE_URL"")
}
model Reminder {
id String @id @default(cuid()) // Unique identifier
recipient String // Phone number to send the SMS to (E.164 format recommended)
message String // The content of the reminder message
sendAt DateTime // The scheduled time for sending (Store in UTC!)
status String @default(""PENDING"") // PENDING, SENT, FAILED (Consider adding: RETRYING, DELIVERED, UNDELIVERABLE with webhooks)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Optional: Add retry count for better error handling
// retryCount Int @default(0)
// Optional: Store failure reason
// failureReason String?
// Index for efficient querying by the scheduler
@@index([sendAt, status])
}
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 on sendAt and status, 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.
npx prisma migrate dev --name initial-reminder-schema
This command will:
- Create a migrations folder inside prisma.
- Generate a SQL file describing the changes needed to create the Reminder table.
- Apply these changes to your PostgreSQL database specified in DATABASE\_URL.
- Generate the Prisma Client based on your schema (npx prisma generate).
2.3 Initialize Prisma Client
Create a singleton instance of the Prisma client to be used throughout the application.
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient({
});
export default prisma;
2.4 Create the Reminder Service
This service will contain the business logic for interacting with the Reminder model in the
database.
import prisma from '../config/prisma.js';
import logger from '../config/logger.js';
export const createReminder = async (recipient, message, sendAt) => {
try {
const reminder = await prisma.reminder.create({
data: {
recipient,
message,
sendAt,
status: 'PENDING',
},
});
logger.info(`Reminder created with ID: ${reminder.id}`);
return reminder;
} catch (error) {
logger.error(`Error creating reminder: ${error.message}`, { error });
throw new Error('Failed to create reminder in database.');
}
};
export const findDueReminders = async (now = new Date()) => {
try {
const dueReminders = await prisma.reminder.findMany({
where: {
sendAt: {
lte: now,
},
status: 'PENDING',
},
orderBy: {
sendAt: 'asc',
},
take: 100,
});
return dueReminders;
} catch (error) {
logger.error(`Error finding due reminders: ${error.message}`, { error });
throw new Error('Failed to query due reminders.');
}
};
export const updateReminderStatus = async (reminderId, status, reason = null) => {
try {
const dataToUpdate = {
status: status,
};
const updatedReminder = await prisma.reminder.update({
where: { id: reminderId },
data: dataToUpdate,
});
logger.info(`Updated status for reminder ${reminderId} to ${status}`);
return updatedReminder;
} catch (error) {
if (error.code === 'P2025') {
logger.warn(`Attempted to update status for non-existent reminder ID: ${reminderId}`);
return null;
}
logger.error(`Error updating status for reminder ${reminderId}: ${error.message}`, { status, error });
return null;
}
};
export const findReminderById = async (reminderId) => {
try {
const reminder = await prisma.reminder.findUnique({
where: { id: reminderId },
});
return reminder;
} catch (error) {
logger.error(`Error finding reminder by ID ${reminderId}: ${error.message}`, { error });
throw new Error('Failed to query reminder by ID.');
}
};
export const deletePendingReminder = async (reminderId) => {
try {
const result = await prisma.$transaction(async (tx) => {
const reminder = await tx.reminder.findUnique({
where: { id: reminderId },
});
if (!reminder) {
logger.warn(`Attempted to delete non-existent reminder: ${reminderId}`);
const notFoundError = new Error('Reminder not found.');
notFoundError.statusCode = 404;
throw notFoundError;
}
if (reminder.status !== 'PENDING') {
logger.warn(`Attempted to delete reminder ${reminderId} with status ${reminder.status}`);
const badRequestError = new Error('Cannot delete reminder that is not in PENDING status.');
badRequestError.statusCode = 400;
throw badRequestError;
}
const deletedReminder = await tx.reminder.delete({
where: { id: reminderId },
});
logger.info(`Deleted reminder ${reminderId}`);
return deletedReminder;
});
return result;
} catch (error) {
if (error.statusCode === 400 || error.statusCode === 404) {
throw error;
}
logger.error(`Error deleting reminder ${reminderId}: ${error.message}`, { error });
throw new Error('Failed to delete reminder.');
}
};
export const listReminders = async (page = 1, limit = 20) => {
try {
const skip = (page - 1) * limit;
const [reminders, total] = await prisma.$transaction([
prisma.reminder.findMany({
skip: skip,
take: limit,
orderBy: {
createdAt: 'desc',
},
}),
prisma.reminder.count(),
]);
return {
reminders,
total,
pages: Math.ceil(total / limit),
currentPage: page,
};
} catch (error) {
logger.error(`Error listing reminders: ${error.message}`, { page, limit, error });
throw new Error('Failed to list reminders.');
}
};
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.
import dotenv from 'dotenv';
dotenv.config();
const config = {
nodeEnv: process.env.NODE_ENV || 'development',
port: process.env.PORT || 3000,
databaseUrl: process.env.DATABASE_URL,
infobip: {
baseUrl: process.env.INFOBIP_BASE_URL,
apiKey: process.env.INFOBIP_API_KEY,
},
scheduler: {
cronPattern: process.env.SCHEDULER_CRON_PATTERN || '* * * * *',
},
auth: {
apiKey: process.env.API_SECRET_KEY,
},
logLevel: process.env.LOG_LEVEL || 'info',
};
if (!config.databaseUrl) {
console.error('FATAL ERROR: Missing environment variable: DATABASE_URL');
process.exit(1);
}
if (!config.infobip.baseUrl || !config.infobip.apiKey) {
console.error('FATAL ERROR: Missing Infobip environment variables: INFOBIP_BASE_URL, INFOBIP_API_KEY');
process.exit(1);
}
if (!config.auth.apiKey && config.nodeEnv === 'production') {
console.warn('SECURITY WARNING: API_SECRET_KEY is not set in production environment. API authentication is disabled!');
} else if (!config.auth.apiKey) {
console.warn('INFO: API_SECRET_KEY is not set. API authentication will be skipped (intended for local development only).');
}
export default config;
3.2 Initialize Infobip Client
Set up the Infobip SDK instance.
import { Infobip, AuthType } from '@infobip-api/sdk';
import config from './index.js';
import logger from './logger.js';
let infobipClient;
try {
if (!config.infobip.baseUrl || !config.infobip.apiKey) {
throw new Error('Infobip Base URL or API Key is missing in configuration.');
}
infobipClient = new Infobip({
baseUrl: config.infobip.baseUrl,
apiKey: config.infobip.apiKey,
authType: AuthType.ApiKey,
});
logger.info('Infobip client initialized successfully.');
} catch (error) {
logger.error('FATAL ERROR: Failed to initialize Infobip client:', { message: error.message });
process.exit(1);
}
export default infobipClient;
3.3 Create the SMS Service
This service encapsulates the logic for sending SMS messages via the Infobip SDK.
import infobipClient from '../config/infobip.js';
import logger from '../config/logger.js';
export const sendSms = async (recipient, messageText, sender = 'InfoSMS') => {
logger.info(`Attempting to send SMS to ${recipient}`);
try {
const payload = {
messages: [
{
destinations: [{ to: recipient }],
from: sender,
text: messageText,
},
],
};
const response = await infobipClient.channels.sms.send(payload);
const messageResult = response?.data?.messages?.[0];
if (messageResult && (messageResult.status?.groupId === 1 || messageResult.status?.groupId === 3)) {
logger.info(`SMS submitted successfully to Infobip for ${recipient}. Message ID: ${messageResult.messageId}, Status: ${messageResult.status.name} (${messageResult.status.description})`);
return {
success: true,
messageId: messageResult.messageId,
status: messageResult.status,
error: null,
};
} else {
const statusDescription = messageResult?.status?.description || 'Unknown status';
const errorCode = messageResult?.status?.id || 'N/A';
const groupName = messageResult?.status?.groupName || 'UNKNOWN_GROUP';
logger.error(`Infobip API reported issue sending SMS to ${recipient}: ${statusDescription} (Code: ${errorCode}, Group: ${groupName})`, { responseData: response?.data });
return {
success: false,
messageId: messageResult?.messageId || null,
status: messageResult?.status || null,
error: `Infobip API Error: ${statusDescription} (Code: ${errorCode}, Group: ${groupName})`,
};
}
} catch (error) {
const statusCode = error?.response?.status;
let apiErrorData = error?.response?.data;
let errorMessage = error.message;
if (apiErrorData?.requestError?.serviceException?.text) {
errorMessage = apiErrorData.requestError.serviceException.text;
} else if (apiErrorData?.messages?.[0]?.status?.description) {
errorMessage = apiErrorData.messages[0].status.description;
} else if (typeof apiErrorData === 'string' && apiErrorData.length > 0) {
errorMessage = apiErrorData;
}
logger.error(`Failed to send SMS via Infobip to ${recipient}: ${errorMessage}`, {
statusCode: statusCode,
apiError: apiErrorData,
originalError: error.message,
});
return {
success: false,
messageId: null,
status: null,
error: `Infobip SDK/API Error: ${errorMessage}${statusCode ? ` (Status Code: ${statusCode})` : ''}`,
};
}
};
Key points:
- We use the @infobip-api/sdk for interaction.
- The 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.
- Error handling distinguishes between SDK/network errors (in catch) and API-reported errors within a successful (2xx) response. More detailed error message extraction is attempted.
- We check 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
import cron from 'node-cron';
import config from '../config/index.js';
import logger from '../config/logger.js';
import { findDueReminders, updateReminderStatus } from './reminderService.js';
import { sendSms } from './smsService.js';
let cronJob = null;
let isRunning = false;
const processDueReminders = async () => {
if (isRunning) {
logger.warn('Scheduler job processing is already in progress. Skipping this cycle.');
return;
}
isRunning = true;
logger.info('Scheduler job started: Checking for due reminders...');
try {
const now = new Date();
const dueReminders = await findDueReminders(now);
if (dueReminders.length === 0) {
logger.info('No due reminders found.');
} else {
logger.info(`Processing ${dueReminders.length} due reminders...`);
for (const reminder of dueReminders) {
logger.info(`Processing reminder ID: ${reminder.id} for ${reminder.recipient}`);
try {
const smsResult = await sendSms(reminder.recipient, reminder.message);
if (smsResult.success) {
await updateReminderStatus(reminder.id, 'SENT');
logger.info(`Successfully sent reminder ${reminder.id} and updated status to SENT.`);
} else {
await updateReminderStatus(reminder.id, 'FAILED', smsResult.error);
logger.error(`Failed to send reminder ${reminder.id}: ${smsResult.error}. Status updated to FAILED.`);
}
} catch (processError) {
logger.error(`Error processing reminder ${reminder.id}: ${processError.message}`, { error: processError });
try {
await updateReminderStatus(reminder.id, 'FAILED', processError.message);
} catch (updateErr) {
logger.error(`Failed to update status to FAILED for reminder ${reminder.id} after processing error: ${updateErr.message}`);
}
}
}
}
} catch (error) {
logger.error(`Scheduler job failed during reminder lookup: ${error.message}`, { error });
} finally {
isRunning = false;
logger.info('Scheduler job finished.');
}
};
export const startScheduler = () => {
if (cronJob) {
logger.warn('Scheduler already started.');
return;
}
const cronPattern = config.scheduler.cronPattern;
if (!cron.validate(cronPattern)) {
logger.error(`Invalid cron pattern: ""${cronPattern}"". Scheduler not started.`);
return;
}
logger.info(`Starting scheduler with pattern: ${cronPattern}`);
cronJob = cron.schedule(cronPattern, processDueReminders, {
scheduled: true,
timezone: ""Etc/UTC""
});
};
export const stopScheduler = () => {
if (cronJob) {
logger.info('Stopping scheduler...');
cronJob.stop();
cronJob = null;
logger.info('Scheduler stopped.');
} else {
logger.warn('Scheduler is not running or already stopped.');
}
};
Key aspects:
node-cron: Used to schedule the processDueReminders function based on the SCHEDULER\_CRON\_PATTERN from the .env file.- UTC Timezone: The cron job is configured to run based on UTC (timezone: ""Etc/UTC""). This is critical for consistency, as reminder sendAt times are stored in UTC.
- Concurrency Lock (
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. - Error Handling: Errors during the database query or within the loop for a single reminder are caught to prevent the entire scheduler from crashing. Failed reminders are marked FAILED. Note: This version lacks sophisticated retry logic.
- Batching: findDueReminders fetches reminders in batches (take: 100) to avoid loading too many into memory.
- Graceful Shutdown: Handled in server.js which calls stopScheduler.
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.
import winston from 'winston';
import config from './index.js';
const { combine, timestamp, json, printf, colorize, errors } = winston.format;
const consoleFormat = printf(({ level, message, timestamp, stack, ...metadata }) => {
let msg = `${timestamp} [${level}]: ${message}`;
const meta = Object.keys(metadata).length > 0 ? JSON.stringify(metadata, null, 2) : '';
if (meta) {
msg += ` ${meta}`;
}
if (stack) {
msg += `\n${stack}`;
}
return msg;
});
const logger = winston.createLogger({
level: config.logLevel || 'info',
format: combine(
errors({ stack: true }),
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
json()
),
transports: [
new winston.transports.Console({
format: combine(
config.nodeEnv === 'development' ? colorize() : winston.format.uncolorize(),
consoleFormat
),
handleExceptions: true,
}),
],
exitOnError: false,
});
logger.stream = {
write: (message) => {
logger.info(message.trim());
},
};
export default logger;
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 β