Developer Quick-Start: A guide to building a Node.js/Express application for scheduling and sending SMS reminders using the Infobip API, Prisma, and node-cron. 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.
Automating communication is crucial for engaging users and streamlining operations. Sending timely reminders β for appointments, payments, or events β is a common requirement. This guide provides a complete walkthrough for building a production-ready system in Node.js and Express to schedule and send SMS reminders using the Infobip API and its Node.js SDK.
We will build an API endpoint to accept reminder requests and a background scheduler that checks for due reminders and dispatches them via Infobip SMS. This approach gives you full control over the scheduling logic within your application while leveraging Infobip's robust communication infrastructure.
Project Overview and Goals
Goal
To create a Node.js Express application that can:
- Accept API requests to schedule an SMS reminder for a specific phone number at a future time.
- Store these scheduled reminders persistently.
- Run a background job to periodically check for reminders that are due.
- Send the due reminders as SMS messages using the Infobip API.
- Provide basic logging, error handling, and configuration management.
Problem Solved
This system solves the challenge of reliably sending automated, time-sensitive SMS notifications without manual intervention, improving user engagement and reducing missed appointments or deadlines.
Technologies
- Node.js: Asynchronous JavaScript runtime for building the backend.
- Express: Minimalist web framework for Node.js to create the API layer.
- Infobip Node.js SDK: To interact with the Infobip SMS API easily and reliably.
node-cron: Task scheduler library for running background jobs within Node.js.- PostgreSQL: Relational database for persistently storing reminder data.
- Prisma: Next-generation ORM for Node.js and TypeScript, used for database schema management, migrations, and type-safe database access.
dotenv: For managing environment variables.
System Architecture
graph LR
A[Client/User] --> B{Express API Server};
B -- POST /api/reminders --> C[Reminder Controller];
C -- Save Reminder --> D[(PostgreSQL Database)];
E[Node-Cron Scheduler] -- Runs Periodically --> F[Check Due Reminders Service];
F -- Fetch Due Reminders --> D;
F -- Send Reminder --> G[Infobip Service];
G -- Use SDK --> H{Infobip SMS API};
H -- Sends SMS --> I[End User Phone];
subgraph Node.js Application
B; C; E; F; G;
end
Outcome
By the end of this guide, you will have a functional Express application with an API endpoint
(POST /api/reminders) to schedule SMS messages and a background worker that sends these messages
at the specified time via Infobip.
Prerequisites
- Node.js (v18 or later recommended) and npm/yarn installed.
- Access to a PostgreSQL database instance. (See Section 6 for notes on setup).
- An active Infobip account (a free trial account works for testing - see Section 11 caveats).
- Basic familiarity with Node.js, Express, APIs, and databases.
1. Setting up the project
Let's start by creating the project structure and installing necessary dependencies.
Environment Setup
Ensure Node.js and npm (or yarn) are installed. You can download Node.js from the official website. Verify the installation:
node -v
npm -v
Project Initialization
- Create Project Directory:
mkdir node-infobip-scheduler
cd node-infobip-scheduler
- Initialize npm Project:
npm init -y
This creates a package.json file.
- Install Dependencies:
npm install express dotenv node-cron
npm install @infobip-api/sdk
npm install prisma --save-dev
npm install @prisma/client
npm install express-validator libphonenumber-js
npm install winston
- Initialize Prisma:
npx prisma init --datasource-provider postgresql
This creates a prisma directory with a schema.prisma file and a .env
file for database connection details.
Project Structure
Organize your project for maintainability:
node-infobip-scheduler/
βββ prisma/
β βββ schema.prisma # Prisma schema definition
β βββ migrations/ # Database migrations (created later)
βββ src/
β βββ config/ # Configuration files (e.g., logger)
β βββ controllers/ # API request handlers
β βββ jobs/ # Background job definitions (node-cron)
β βββ middleware/ # Express middleware (e.g., auth, error handling)
β βββ routes/ # API route definitions
β βββ services/ # Business logic and external service interactions
β βββ utils/ # Utility functions (e.g., validators)
β βββ index.js # Main application entry point
βββ .env # Environment variables (DATABASE_URL, Infobip keys)
βββ package.json
βββ package-lock.json
βββ README.md
Configure Environment Variables (.env)
Prisma already added DATABASE_URL. Add placeholders for Infobip credentials and the server port.
Replace placeholders later with actual values.
.env
# .env
# Database Connection (Prisma format)
# Example: postgresql://user:password@host:port/database?schema=public
DATABASE_URL=""postgresql://...""
# Server Configuration
PORT=3000
# Infobip Credentials
# Find these in your Infobip portal:
# INFOBIP_API_KEY: Go to Developers -> API Keys. Create/copy the key value.
INFOBIP_API_KEY=YOUR_INFOBIP_API_KEY
# INFOBIP_BASE_URL: Find on portal homepage or under Developers -> API Keys (e.g., youraccount.api.infobip.com).
INFOBIP_BASE_URL=YOUR_INFOBIP_BASE_URL
# Optional: A simple API key for securing your scheduling endpoint
# IMPORTANT: For production, use a strong, randomly generated key.
API_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY
Purpose: Using .env keeps sensitive information like API keys and database URLs
out of your codebase, adhering to security best practices. dotenv library loads these variables
into process.env.
Basic Express Server Setup (src/index.js)
require('dotenv').config();
const express = require('express');
const reminderRoutes = require('./routes/reminderRoutes');
const { basicAuth } = require('./middleware/authMiddleware');
const { errorHandler } = require('./middleware/errorMiddleware');
const logger = require('./config/logger');
const initializeScheduler = require('./jobs/reminderScheduler');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use((req, res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
});
app.use('/api/reminders', basicAuth, reminderRoutes);
app.get('/health', (req, res) => {
res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() });
});
app.use(errorHandler);
app.listen(PORT, () => {
logger.info(`Server running on port ${PORT}`);
initializeScheduler();
logger.info('Reminder scheduler initialized.');
});
module.exports = app;
Why: This sets up a basic Express server, loads environment variables, includes JSON parsing, defines a simple health check, wires up routes (created later), includes middleware for auth and errors (defined later), and starts the server. Crucially, it also initializes the reminder scheduler job.
Note on Dependencies: Notice the require statements for logger,
basicAuth, and errorHandler. The actual code for these modules will be created in
later sections (Sections 5 and 3, respectively). If running incrementally, these lines would cause errors
until those modules exist.
2. Implementing core functionality (Scheduler)
We'll use node-cron to periodically check for reminders that need to be sent.
Create the Scheduler Job (src/jobs/reminderScheduler.js)
const cron = require('node-cron');
const { PrismaClient } = require('@prisma/client');
const infobipService = require('../services/infobipService');
const logger = require('../config/logger');
const prisma = new PrismaClient();
const cronSchedule = '* * * * *';
let taskRunning = false;
const checkAndSendReminders = async () => {
if (taskRunning) {
logger.warn('Reminder job already running, skipping this cycle.');
return;
}
taskRunning = true;
logger.info('Running scheduled reminder check...');
try {
const now = new Date();
const dueReminders = await prisma.reminder.findMany({
where: {
sendAt: {
lte: now,
},
status: 'PENDING',
},
take: 100,
orderBy: {
sendAt: 'asc',
},
});
logger.info(`Found ${dueReminders.length} due reminders.`);
if (dueReminders.length === 0) {
taskRunning = false;
return;
}
for (const reminder of dueReminders) {
try {
logger.info(`Attempting to send reminder ID: ${reminder.id} to ${reminder.phoneNumber}`);
await infobipService.sendSms(reminder.phoneNumber, reminder.message);
await prisma.reminder.update({
where: { id: reminder.id },
data: { status: 'SENT' },
});
logger.info(`Reminder ID: ${reminder.id} sent successfully.`);
} catch (sendError) {
logger.error(`Failed to send reminder ID: ${reminder.id}. Error: ${sendError.message}`, { error: sendError });
try {
await prisma.reminder.update({
where: { id: reminder.id },
data: { status: 'FAILED' },
});
} catch (updateError) {
logger.error(`Failed to update status for reminder ID: ${reminder.id} after send failure. Error: ${updateError.message}`, { error: updateError });
}
}
}
} catch (error) {
logger.error(`Error during reminder check: ${error.message}`, { error: error });
} finally {
taskRunning = false;
logger.info('Reminder check finished.');
}
};
const initializeScheduler = () => {
if (!cron.validate(cronSchedule)) {
logger.error(`Invalid cron schedule: ${cronSchedule}. Scheduler not started.`);
return;
}
cron.schedule(cronSchedule, checkAndSendReminders, {
scheduled: true,
timezone: ""UTC""
});
logger.info(`Scheduler started with schedule: ${cronSchedule} in UTC timezone.`);
};
module.exports = initializeScheduler;
Why node-cron
It's a simple, widely used library for scheduling tasks within a Node.js process. Perfect for periodic jobs like checking for due reminders.
Logic
- Runs on a defined schedule (e.g., every minute).
- Uses a simple taskRunning flag as a mutex. Caveat: This simple flag might not be fully robust in edge cases like unhandled promise rejections before the flag is reset or in distributed environments. Consider Redis-based locks or similar for higher guarantees if needed.
- Queries the database (using Prisma) for reminders where sendAt is in the past or present (UTC) and status is 'PENDING'.
- Fetches reminders in batches (take: 100) to manage load.
- Iterates through due reminders, calling the infobipService (defined later) to send the SMS.
- Updates the reminder status to 'SENT' or 'FAILED' based on the outcome.
- Includes error handling for both sending SMS and database updates.
- Logs progress and errors (using logger, defined later).
- Uses UTC for scheduling and querying to avoid timezone issues.
Integration
The initializeScheduler function is exported and called in src/index.js when the
server starts.
3. Building a complete API layer (Scheduling Endpoint)
We need an API endpoint for clients to submit reminder requests.
Define Routes (src/routes/reminderRoutes.js)
const express = require('express');
const reminderController = require('../controllers/reminderController');
const { validateReminder } = require('../utils/validators');
const router = express.Router();
router.post('/', validateReminder, reminderController.scheduleReminder);
module.exports = router;
Why: This file defines the specific HTTP methods and paths for reminder-related actions, linking them to controller functions and applying validation middleware.
Implement Controller (src/controllers/reminderController.js)
const { PrismaClient } = require('@prisma/client');
const { validationResult } = require('express-validator');
const logger = require('../config/logger');
const { parsePhoneNumberWithError } = require('libphonenumber-js');
const prisma = new PrismaClient();
exports.scheduleReminder = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
logger.warn('Validation failed for scheduleReminder request.', { errors: errors.array() });
return res.status(400).json({ errors: errors.array() });
}
const { phoneNumber, message, sendAt } = req.body;
try {
let formattedPhoneNumber;
try {
const parsedNumber = parsePhoneNumberWithError(phoneNumber);
if (!parsedNumber || !parsedNumber.isValid()) {
throw new Error('Invalid phone number format or number.');
}
formattedPhoneNumber = parsedNumber.format('E.164');
} catch (phoneError) {
logger.warn(`Invalid phone number provided: ${phoneNumber}`, { error: phoneError.message });
return res.status(400).json({ errors: [{ msg: `Invalid phone number: ${phoneError.message}` }] });
}
const sendAtDate = new Date(sendAt);
if (isNaN(sendAtDate.getTime()) || sendAtDate <= new Date()) {
logger.warn(`Invalid sendAt date provided: ${sendAt}. Must be in the future.`);
return res.status(400).json({ errors: [{ msg: 'sendAt must be a valid ISO 8601 timestamp in the future.' }] });
}
const newReminder = await prisma.reminder.create({
data: {
phoneNumber: formattedPhoneNumber,
message: message,
sendAt: sendAtDate,
status: 'PENDING',
},
});
logger.info(`Reminder scheduled successfully with ID: ${newReminder.id}`);
res.status(201).json({
message: 'Reminder scheduled successfully.',
reminderId: newReminder.id,
status: newReminder.status,
scheduledAt: newReminder.createdAt,
sendAt: newReminder.sendAt,
});
} catch (error) {
logger.error(`Error scheduling reminder: ${error.message}`, { error });
next(error);
}
};
Why: The controller handles the core logic for the API endpoint.
- It uses express-validator results to check for bad input.
- It uses libphonenumber-js to validate and format the phone number to E.164 standard, crucial for reliable international SMS sending.
- It validates the sendAt timestamp, ensuring it's a valid date in the future. Clarified that scheduling in the immediate same minute might be prevented by the < new Date() check.
- It interacts with the database (via Prisma) to create a new reminder record with a 'PENDING' status.
- It returns a success response with the ID of the newly created reminder.
- It passes any unexpected errors to the central error handling middleware (next(error)).
Implement Basic Authentication Middleware (src/middleware/authMiddleware.js)
const logger = require('../config/logger');
const basicAuth = (req, res, next) => {
const providedKey = req.headers['x-api-key'];
const expectedKey = process.env.API_ACCESS_KEY;
if (!expectedKey) {
logger.error('CRITICAL: API_ACCESS_KEY is not set in environment variables. Denying all requests to protected endpoints.');
return res.status(500).json({ message: 'Server configuration error.' });
}
if (!providedKey || providedKey !== expectedKey) {
logger.warn('Unauthorized access attempt: Invalid or missing API key.');
return res.status(401).json({ message: 'Unauthorized: Invalid API Key.' });
}
next();
};
module.exports = { basicAuth };
Why: Protects the scheduling endpoint from unauthorized access. This is a very
basic example using a static API key passed in a header (x-api-key). Added a warning recommending
stronger methods for production.
Implement Request Validation (src/utils/validators.js)
const { body } = require('express-validator');
const validateReminder = [
body('phoneNumber')
.trim()
.notEmpty().withMessage('phoneNumber is required.')
.isString().withMessage('phoneNumber must be a string.')
.isLength({ min: 8, max: 20 }).withMessage('phoneNumber has invalid length.'),
body('message')
.trim()
.notEmpty().withMessage('message is required.')
.isString().withMessage('message must be a string.')
.isLength({ min: 1, max: 1600 }).withMessage('message must be between 1 and 1600 characters.')
,
body('sendAt')
.notEmpty().withMessage('sendAt is required.')
.isISO8601().withMessage('sendAt must be a valid ISO 8601 timestamp (UTC recommended, e.g., YYYY-MM-DDTHH:mm:ss.sssZ).')
,
];
module.exports = { validateReminder };
Why: Uses express-validator to define rules for incoming request bodies.
Ensures required fields are present, have the correct types, and meet basic constraints (like message length).
This prevents invalid data from reaching the controller logic.
API Endpoint Documentation & Testing
You can test the POST /api/reminders endpoint using curl or Postman.
curl Example:
Replace placeholders with your actual values.
curl -X POST http://localhost:3000/api/reminders \
-H ""Content-Type: application/json"" \
-H ""x-api-key: YOUR_SECRET_ACCESS_KEY"" \
-d '{
""phoneNumber"": ""+14155551234"",
""message"": ""Your appointment is tomorrow at 10 AM."",
""sendAt"": ""2025-04-21T10:00:00.000Z""
}'
Request Body (JSON):
{
""phoneNumber"": ""+14155551234"",
""message"": ""Your appointment is tomorrow at 10 AM."",
""sendAt"": ""2025-04-21T10:00:00.000Z""
}
Success Response (JSON):
{
""message"": ""Reminder scheduled successfully."",
""reminderId"": ""clv..."",
""status"": ""PENDING"",
""scheduledAt"": ""2025-04-20T15:30:00.123Z"",
""sendAt"": ""2025-04-21T10:00:00.000Z""
}
Error Response (JSON - Validation Example):
{
""errors"": [
{
""type"": ""field"",
""value"": ""invalid-date"",
""msg"": ""sendAt must be a valid ISO 8601 timestamp (UTC recommended, e.g., YYYY-MM-DDTHH:mm:ss.sssZ)."",
""path"": ""sendAt"",
""location"": ""body""
}
]
}
4. Integrating with Infobip
Now, let's implement the service that uses the Infobip Node.js SDK to send SMS messages.
Create Infobip Service (src/services/infobipService.js)
const { Infobip, AuthType } = require('@infobip-api/sdk');
const logger = require('../config/logger');
if (!process.env.INFOBIP_BASE_URL || !process.env.INFOBIP_API_KEY) {
logger.error('CRITICAL: Infobip environment variables (INFOBIP_BASE_URL, INFOBIP_API_KEY) are not set.');
throw new Error('Missing Infobip configuration in environment variables.');
}
let infobipClient;
try {
infobipClient = new Infobip({
baseUrl: process.env.INFOBIP_BASE_URL,
apiKey: process.env.INFOBIP_API_KEY,
authType: AuthType.ApiKey,
});
logger.info('Infobip client initialized successfully.');
} catch (error) {
logger.error(`FATAL: Failed to initialize Infobip client: ${error.message}`, { error });
infobipClient = null;
}
const sendSms = async (toPhoneNumber, messageText) => {
if (!infobipClient) {
logger.error('Infobip client is not initialized. Cannot send SMS.');
throw new Error('Infobip client is not initialized.');
}
if (!toPhoneNumber || !messageText) {
logger.error('Missing recipient phone number or message text in sendSms call.');
throw new Error('Missing recipient phone number or message text.');
}
const payload = {
messages: [
{
destinations: [{ to: toPhoneNumber }],
text: messageText,
},
],
};
try {
logger.info(`Sending SMS via Infobip to ${toPhoneNumber}. Message length: ${messageText.length}`);
const response = await infobipClient.channels.sms.send(payload);
const messageResponse = response.data?.messages?.[0];
if (messageResponse) {
logger.info(`Infobip SMS submitted successfully. To: ${toPhoneNumber}, Message ID: ${messageResponse.messageId}, Status Group: ${messageResponse.status?.groupName} (${messageResponse.status?.description})`);
} else {
logger.warn(`Infobip response structure unexpected for SMS to ${toPhoneNumber}.`, { responseData: response.data });
}
if (messageResponse?.status?.groupId && ![1, 3].includes(messageResponse.status.groupId)) {
logger.warn(`Infobip reported non-successful status group for SMS to ${toPhoneNumber}: ${messageResponse.status.groupName} - ${messageResponse.status.description} (ID: ${messageResponse.status.id})`);
}
return response.data;
} catch (error) {
const errorDetails = error.response?.data || error.message;
logger.error(`Infobip API error sending SMS to ${toPhoneNumber}: ${error.message}`, {
error: errorDetails,
status: error.response?.status,
payloadSummary: {
to: toPhoneNumber,
messageLength: messageText.length,
senderIdUsed: payload.messages[0].from || 'Default',
}
});
throw new Error(`Failed to send SMS via Infobip: ${error.message}`);
}
};
module.exports = { sendSms };
Why: This service encapsulates all interaction with the Infobip SDK.
- Initializes the Infobip client using baseUrl and apiKey from environment variables. Added error handling for missing variables and client initialization failure.
- Uses AuthType.ApiKey.
- The sendSms function constructs the payload. Added clarification on the optional from field (Sender ID) and its implications regarding registration, cost, and deliverability.
- Includes robust logging for success and failure. Logs the Infobip messageId and status group.
- Checks the response status group ID for potential issues beyond HTTP errors.
- Modified error logging to log error.response?.data but added a comment warning about potentially sensitive information. Also logs non-sensitive payload parts.
- Re-throws errors for the caller (scheduler job) to handle.
Fallback Strategy
If you need higher resilience, you could implement a fallback mechanism. In the catch block of
checkAndSendReminders (Section 2), instead of immediately marking as FAILED, you could call
another function (e.g., alternativeSmsService.sendSms). This would require:
- Setting up another SMS provider account and credentials.
- Creating a similar service file (src/services/alternativeSmsService.js).
- Adding logic to decide when to use the fallback (e.g., after Infobip fails N times).
5. Implementing error handling, logging, and retry mechanisms
Robust error handling and logging are essential for production systems.
Consistent Error Handling Strategy
- Validation Errors: Handled specifically in controllers (using express-validator) returning 400 status code.
- Authentication Errors: Handled by authMiddleware, returning 401.
- Operational Errors (Expected): Handled within services or jobs (e.g., Infobip API errors, DB connection issues). Logged appropriately, potentially retried (see below), and may result in updating DB status (e.g., FAILED). Handled by the caller or allowed to propagate.
- Programmer Errors (Unexpected): Caught by the global error handler (errorHandler), logged as critical errors, and return a generic 500 status code to the client.
Global Error Handling Middleware (src/middleware/errorMiddleware.js)
const logger = require('../config/logger');
const errorHandler = (err, req, res, next) => {
logger.error('Unhandled error caught by global error handler:', {
message: err.message,
stack: err.stack,
method: req.method,
url: req.originalUrl,
ip: req.ip,
});
if (res.headersSent) {
return next(err);
}
res.status(500).json({
message: 'Internal Server Error. Please try again later.',
});
};
module.exports = { errorHandler };
(Note: The rest of Section 5, including Logger Configuration and Retry Mechanisms, was missing from the
original provided text. This rewrite includes the completed errorHandler based on the
structure.)
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 β