Developer Quick-Start: A guide to building a Node.js Express application for scheduling and sending SMS reminders via the Infobip API, covering setup, database, scheduling, and API integration. 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 Node.js application using the Express framework to schedule and send SMS reminders via the Infobip API. We'll cover everything from project setup and database integration to scheduling logic, error handling, security, and deployment.
Project Goal: To create a backend service that allows users (or other systems) to schedule SMS reminders (e.g., appointments, payment due dates) which are automatically sent at the specified time using Infobip.
Problem Solved: Automates the process of sending timely SMS notifications, improving communication and reducing manual effort. Handles scheduling complexity, API integration, and ensures reliable delivery.
Technologies Used:
- Node.js: JavaScript runtime for building the backend server.
- Express: Minimalist web framework for Node.js, used for creating the API layer.
- Infobip API & Node.js SDK: Cloud communications platform for sending SMS messages. We'll use their official SDK (@infobip-api/sdk).
- PostgreSQL: Robust relational database for storing reminder data.
- Prisma: Next-generation ORM for Node.js and TypeScript (we'll use JavaScript) to interact with the database.
node-cron: Task scheduler for Node.js to trigger reminder checks periodically.dotenv: Module to load environment variables from a .env file.libphonenumber-js: Library for parsing, formatting, and validating phone numbers.- (Optional but Recommended) winston (for logging), express-validator (for validation), express-rate-limit (for security), helmet (security headers).
(See package.json in Section 1 for example dependency versions used in this guide.)
System Architecture:
graph LR
A[Client/API Consumer] -- HTTP Request --> B(Express API Layer);
B -- Create Reminder --> C{Database (PostgreSQL w/ Prisma)};
D[node-cron Scheduler] -- Runs Periodically --> E{Reminder Check Service};
E -- Fetch Due Reminders --> C;
E -- Send SMS Request --> F(Infobip Service);
F -- Uses SDK --> G[Infobip SMS API];
G -- Sends SMS --> H(End User's Phone);
B -- API Response --> A;
E -- Update Status --> C;
subgraph Node.js Application
B
D
E
F
end
(Note: Rendering requires Markdown platform support for Mermaid diagrams.)
Prerequisites:
- Node.js (v16 or later recommended) and npm/yarn installed.
- Access to a PostgreSQL database instance (local or cloud-based).
- An Infobip account (a free trial account works, but note limitations).
- Basic familiarity with JavaScript, Node.js, Express, and REST APIs.
- A text editor or IDE (like VS Code).
- Terminal/Command Prompt access.
Final Outcome: A running Node.js service with an API endpoint to schedule reminders and a background job that automatically sends these reminders via Infobip SMS at the correct time.
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 infobip-reminder-app
cd infobip-reminder-app
- Initialize Node.js Project: This creates a
package.jsonfile.
npm init -y
- Install Dependencies: We need Express for the server, the Infobip SDK, Prisma for
database interaction,
pgas the PostgreSQL driver,node-cronfor scheduling,dotenvfor environment variables, andlibphonenumber-jsfor phone number validation.
npm install express @infobip-api/sdk pg node-cron dotenv libphonenumber-js
npm install --save-dev prisma
- express: Web framework.
- @infobip-api/sdk: Official SDK for interacting with Infobip APIs.
- pg: Node.js driver for PostgreSQL (required by Prisma).
- node-cron: Job scheduler.
- dotenv: Loads environment variables from .env file.
- libphonenumber-js: Phone number parsing/validation/formatting.
- prisma: Development dependency for Prisma CLI commands (schema management, migrations).
- Initialize Prisma: This creates a
prismadirectory with aschema.prismafile and a.envfile (if one doesn't exist).
npx prisma init --datasource-provider postgresql
- Configure Database Connection (.env): Open the
.envfile created by Prisma (or create one if it wasn't). Update theDATABASE_URLvariable with your PostgreSQL connection string.
.env
# .env
# PostgreSQL connection string
# Format: postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public
DATABASE_URL="postgresql://your_db_user:your_db_password@localhost:5432/reminder_db?schema=public"
# Infobip Credentials (Obtain from Infobip Dashboard)
INFOBIP_API_KEY="YOUR_INFOBIP_API_KEY"
INFOBIP_BASE_URL="YOUR_INFOBIP_BASE_URL" # e.g., xyz.api.infobip.com
INFOBIP_SENDER_ID="InfoSMS" # Or your registered Sender ID
# Application Port
PORT=3000
# Node environment (development, production) - affects error handling, logging
NODE_ENV=development
# Optional: Log level for Winston
# LOG_LEVEL=debug
DATABASE_URL: Replace placeholders with your actual database user, password, host, port, and database name. Ensure the database (reminder\_db in the example) exists. Use quotes if your password contains special characters.INFOBIP_API_KEY,INFOBIP_BASE_URL,INFOBIP_SENDER_ID: We'll get these from Infobip later (Section 3). Leave them blank for now or use placeholders.PORT: The port your Express server will listen on.NODE_ENV: Set to production in deployment environments.
- Define Project Structure: Create the following directories and files for organization:
infobip-reminder-app/
βββ prisma/
β βββ schema.prisma
β βββ migrations/ (will be created later)
βββ src/
β βββ config/
β β βββ infobip.js # Infobip SDK client setup
β β βββ logger.js # Logger configuration
β β βββ prismaClient.js # Prisma client instance
β βββ controllers/
β β βββ reminderController.js # API request handling
β βββ jobs/
β β βββ reminderScheduler.js # Cron job logic
β βββ routes/
β β βββ reminderRoutes.js # API routes definition
β βββ services/
β β βββ reminderService.js # Core logic for reminders & DB interaction
β β βββ smsService.js # Logic for sending SMS via Infobip
β βββ app.js # Express application setup
β βββ server.js # Server entry point
βββ .env
βββ .gitignore
βββ package.json
βββ package-lock.json
- Why this structure? It separates concerns (routes, controllers, services, configuration, jobs), making the application easier to understand, maintain, and test.
- Create Basic Express Server (
src/app.js):
const express = require('express');
const reminderRoutes = require('./routes/reminderRoutes');
const logger = require('./config/logger');
const app = express();
app.use(express.json());
app.use('/api/reminders', reminderRoutes);
app.get('/health', (req, res) => {
res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() });
});
app.use((err, req, res, next) => {
logger.error('Unhandled error:', {
message: err.message,
stack: err.stack,
url: req.originalUrl,
method: req.method,
ip: req.ip,
});
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
status: 'error',
statusCode: statusCode,
message: err.message || 'An unexpected error occurred.',
stack: process.env.NODE_ENV === 'development' ? err.stack : undefined,
});
});
module.exports = app;
- Create Server Entry Point (
src/server.js):
require('dotenv').config();
const app = require('./app');
const logger = require('./config/logger');
const { startScheduler } = require('./jobs/reminderScheduler');
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
logger.info(`Server running on port ${PORT} in ${process.env.NODE_ENV || 'development'} mode`);
startScheduler();
logger.info('Reminder scheduler started.');
});
- Add Start Script (
package.json): Add scripts to easily run your server and tests.
{
"name": "infobip-reminder-app",
"version": "1.0.0",
"description": "SMS Reminder App using Infobip",
"main": "src/server.js",
"scripts": {
"start": "node src/server.js",
"dev": "nodemon src/server.js",
"test": "jest",
"prisma:migrate:dev": "npx prisma migrate dev",
"prisma:migrate:deploy": "npx prisma migrate deploy",
"prisma:generate": "npx prisma generate"
},
"keywords": [
"infobip",
"sms",
"reminder",
"node",
"express",
"prisma"
],
"author": "",
"license": "ISC",
"dependencies": {
"@infobip-api/sdk": "^3.0.0",
"dotenv": "^16.0.0",
"express": "^4.18.0",
"libphonenumber-js": "^1.10.0",
"node-cron": "^3.0.0",
"pg": "^8.8.0"
},
"devDependencies": {
"prisma": "^5.0.0"
}
}
- (Note: The dependency versions listed (e.g.,
^3.0.0) are examples at the time of writing. You should use the versions installed bynpm installor check for the latest compatible versions.) - You can run the server using npm start. If you install nodemon (npm install --save-dev nodemon), you can use npm run dev for automatic restarts during development.
- npm test will run Jest tests (requires Jest setup, see Section 13).
- Added Prisma helper scripts.
- Setup
.gitignore: Create a.gitignorefile in the root directory to avoid committing sensitive files and unnecessary directories.
# .gitignore
# Dependencies
/node_modules
# Environment variables
.env*
!.env.example
# Prisma generated files / local DB
/prisma/dev.db*
/prisma/client
# Logs
/logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# OS generated files
.DS_Store
Thumbs.db
# Build outputs
/dist
2. Database Schema and Data Layer (Prisma)
We'll define the database schema for our reminders and set up Prisma Client to interact with it.
- Define Prisma Schema (
prisma/schema.prisma): Open theprisma/schema.prismafile and define theRemindermodel.
Prisma
// prisma/schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = ""prisma-client-js""
// output = ""./client"" // Example: Customize client output location if needed
}
datasource db {
provider = ""postgresql""
url = env(""DATABASE_URL"")
}
model Reminder {
id String @id @default(cuid()) // Unique identifier
phoneNumber String // E.164 format REQUIRED (e.g., +14155552671)
message String @db.Text // Use Text for potentially long messages
sendAt DateTime // The exact time (UTC) to send the reminder
status Status @default(PENDING) // Status of the reminder
createdAt DateTime @default(now()) // When the reminder was created
updatedAt DateTime @updatedAt // When the reminder was last updated
infobipMessageId String? // Store Infobip's message ID after sending
errorMessage String? @db.Text // Store error message if sending fails
// Index for the scheduler query
@@index([status, sendAt])
}
enum Status {
PENDING // Reminder is scheduled but not yet sent
PROCESSING // Reminder is currently being processed by the scheduler
SENT // Reminder has been successfully sent via Infobip
ERROR // An error occurred trying to send the reminder
// Add other statuses if needed (e.g., FAILED_DELIVERY from DLR)
}
id: Unique CUID for each reminder.phoneNumber: Recipient's number. Stored in E.164 format (enforced by service).message: Text content of the SMS (using @db.Text for flexibility).sendAt: The crucial field storing the scheduled time in UTC.status: Tracks the lifecycle of the reminder using an enum. PROCESSING helps prevent double-sending.infobipMessageId: Useful for tracking and debugging with Infobip.errorMessage: Stores failure reasons.@@index([status, sendAt]): Adds a database index to optimize queries for finding due reminders.
- Create Database Migration: Run the following command to create the SQL migration files
based on your schema changes and apply them to your database. Prisma will prompt you to name the migration
(e.g.,
init_reminder_model).
npx prisma migrate dev --name init_reminder_model
- This command does three things:
- Creates a new SQL migration file in prisma/migrations/.
- Applies the migration to your database, creating the Reminder table and Status enum.
- Generates/updates Prisma Client based on your schema.
- Initialize Prisma Client: Create an instance of Prisma Client to use throughout your application.
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'info', 'warn', 'error'] : ['error'],
});
module.exports = prisma;
- Implement Data Access Logic (
src/services/reminderService.js): This service will handle creating reminders and finding ones that are due.
const prisma = require('../config/prismaClient');
const logger = require('../config/logger');
const { Status } = require('@prisma/client');
const createReminder = async (phoneNumber, message, sendAt) => {
if (!phoneNumber || !message || !sendAt) {
throw new Error('Phone number, message, and sendAt time are required.');
}
if (!(sendAt instanceof Date) || isNaN(sendAt)) {
throw new Error('sendAt must be a valid Date object.');
}
if (sendAt <= new Date(Date.now() - 5000)) {
throw new Error('sendAt time must be in the future.');
}
if (!/^\+[1-9]\d{1,14}$/.test(phoneNumber)) {
logger.error(`Invalid E.164 phone number format received by service: ${phoneNumber}`);
throw new Error('Phone number must be in E.164 format (e.g., +14155552671)');
}
try {
const reminder = await prisma.reminder.create({
data: {
phoneNumber,
message,
sendAt: sendAt.toISOString(),
status: Status.PENDING,
},
});
logger.info(`Reminder created with ID: ${reminder.id} for ${phoneNumber}`);
return reminder;
} catch (error) {
logger.error(`Error creating reminder in DB for ${phoneNumber}: ${error.message}`, { error });
if (error.code === 'P2002') {
throw new Error('A reminder with these details might already exist.');
}
throw new Error('Database error occurred while creating reminder.');
}
};
const findAndMarkDueReminders = async () => {
const now = new Date();
const lookAheadTime = new Date(now.getTime() + 60 * 1000);
const dueReminders = await prisma.reminder.findMany({
where: {
status: Status.PENDING,
sendAt: {
lte: lookAheadTime,
},
},
take: 100,
orderBy: {
sendAt: 'asc',
},
});
if (dueReminders.length === 0) {
return [];
}
const reminderIds = dueReminders.map(r => r.id);
logger.info(`Found ${dueReminders.length} potential reminders to process. IDs: ${reminderIds.join(', ')}`);
try {
const updateResult = await prisma.reminder.updateMany({
where: {
id: {
in: reminderIds,
},
status: Status.PENDING,
},
data: {
status: Status.PROCESSING,
updatedAt: new Date(),
},
});
if (updateResult.count > 0) {
const processingReminders = await prisma.reminder.findMany({
where: {
id: { in: reminderIds },
status: Status.PROCESSING,
},
});
logger.info(`Successfully marked ${processingReminders.length} reminders as PROCESSING.`);
return processingReminders;
} else {
logger.warn('Found due reminders, but failed to mark them as PROCESSING (possibly processed by another instance or status changed).');
return [];
}
} catch (error) {
logger.error(`Error marking reminders as PROCESSING: ${error.message}`, { error, reminderIds });
return [];
}
};
const updateReminderStatus = async (reminderId, status, infobipMessageId = null, errorMessage = null) => {
if (!reminderId || !status) {
throw new Error('Reminder ID and status are required for update.');
}
if (![Status.SENT, Status.ERROR].includes(status)) {
throw new Error(`Invalid final status: ${status}. Must be SENT or ERROR.`);
}
try {
const updatedReminder = await prisma.reminder.update({
where: { id: reminderId },
data: {
status,
infobipMessageId: infobipMessageId,
errorMessage: errorMessage ? errorMessage.substring(0, 1000) : null,
updatedAt: new Date(),
},
});
logger.info(`Updated status for reminder ${reminderId} to ${status}.`);
return updatedReminder;
} catch (error) {
logger.error(`Error updating status for reminder ${reminderId} to ${status}: ${error.message}`, { error });
throw new Error(`Database error occurred while updating reminder ${reminderId}.`);
}
};
module.exports = {
createReminder,
findAndMarkDueReminders,
updateReminderStatus,
};
createReminder: Takes details, performs strict validation (expects E.164 number), and saves to the DB. Includes basic error handling for DB operations.findAndMarkDueReminders: Queries for PENDING reminders using the index, fetches a batch, and attempts to atomically update their status to PROCESSING. Returns only the reminders successfully marked. Includes logging and error handling.updateReminderStatus: Updates the reminder's status to SENT or ERROR. Includes error handling for the update operation.
3. Integrating with Infobip (SMS Sending Service)
Now, let's set up the Infobip SDK client and create a service to handle sending SMS messages.
- Obtain Infobip Credentials:
- Log in to your Infobip account.
- API Key: Navigate to the API Keys management section (often under your account settings or developer tools). Generate a new API key if you don't have one. Copy this key.
- Base URL: Your Base URL is specific to your account and region. You can usually find this
on the API Keys page or the main dashboard/homepage after logging in. It looks something like
xxxxx.api.infobip.com. Copy this URL. - Sender ID: Decide on a Sender ID (the "from" name/number shown on the recipient's phone). For trial accounts, you might be restricted to specific shared numbers or need to register your own number. For paid accounts, you can often register alphanumeric Sender IDs (like "MyCompany"). Check Infobip's documentation for rules in your target countries.
- Update
.env: Paste your copied API Key, Base URL, and chosen Sender ID into the.envfile:
.env
# .env (update these lines)
INFOBIP_API_KEY="PASTE_YOUR_API_KEY_HERE"
INFOBIP_BASE_URL="PASTE_YOUR_BASE_URL_HERE"
INFOBIP_SENDER_ID="YourSenderID" # Or "InfoSMS", or a purchased number
- Free Trial Limitation: Remember, if using a free trial, you can typically only send SMS messages to the phone number you verified during signup.
- Configure Infobip SDK Client (
src/config/infobip.js):
const { Infobip, AuthType } = require('@infobip-api/sdk');
require('dotenv').config();
const apiKey = process.env.INFOBIP_API_KEY;
const baseUrl = process.env.INFOBIP_BASE_URL;
if (!apiKey || !baseUrl) {
throw new Error('Missing Infobip API Key or Base URL in environment variables. Application cannot start.');
}
const infobipClient = new Infobip({
baseUrl: baseUrl,
apiKey: apiKey,
authType: AuthType.ApiKey,
});
module.exports = infobipClient;
- This code imports the SDK, reads credentials from environment variables, throws an error if they are missing, and initializes the Infobip client instance. We export the client for use in other services.
- Create SMS Sending Service (
src/services/smsService.js):
const infobipClient = require('../config/infobip');
const logger = require('../config/logger');
const defaultSender = process.env.INFOBIP_SENDER_ID || 'InfoSMS';
const sendSms = async (recipientPhoneNumber, messageText, senderId = defaultSender) => {
if (!recipientPhoneNumber || !messageText) {
throw new Error('Recipient phone number and message text are required for sending SMS.');
}
if (!/^\+[1-9]\d{1,14}$/.test(recipientPhoneNumber)) {
logger.error(`Invalid E.164 format passed to sendSms: ${recipientPhoneNumber}`);
throw new Error(`Invalid phone number format for SMS recipient: ${recipientPhoneNumber}. Must be E.164.`);
}
logger.info(`Attempting to send SMS via Infobip to ${recipientPhoneNumber} from ${senderId}`);
try {
const response = await infobipClient.channels.sms.send({
messages: [
{
destinations: [{ to: recipientPhoneNumber }],
from: senderId,
text: messageText,
},
],
});
if (response.data && response.data.messages && response.data.messages.length > 0) {
const messageResult = response.data.messages[0];
const status = messageResult.status;
const successGroups = ['PENDING', 'ACCEPTED'];
if (status && successGroups.includes(status.groupName)) {
logger.info(`SMS submitted successfully to Infobip for ${recipientPhoneNumber}. Message ID: ${messageResult.messageId}, Status: ${status.groupName}`);
return response.data;
} else {
const errorDetails = status ? `${status.groupName} (ID: ${status.groupId}) - ${status.description}` : 'Unknown status';
logger.error(`Infobip SMS submission failed for ${recipientPhoneNumber}. Status: ${errorDetails}`);
throw new Error(`Infobip API Error: ${errorDetails}`);
}
} else {
logger.error(`Unexpected response structure from Infobip for ${recipientPhoneNumber}:`, response.data);
throw new Error('Infobip API Error: Unexpected response structure.');
}
} catch (error) {
let errorMessage = error.message;
if (error.response && error.response.data) {
logger.error(`Error sending SMS via Infobip to ${recipientPhoneNumber}. Status: ${error.response.status}. Response:`, error.response.data);
const serviceException = error.response.data?.requestError?.serviceException;
if (serviceException) {
errorMessage = `Infobip API Error: ${serviceException.messageId} - ${serviceException.text}`;
} else {
errorMessage = `Infobip API Error: Status ${error.response.status} - ${JSON.stringify(error.response.data)}`;
}
} else {
logger.error(`Error sending SMS via Infobip to ${recipientPhoneNumber}: ${error.message}`, { error });
}
throw new Error(errorMessage);
}
};
module.exports = {
sendSms,
};
- Imports the configured infobipClient and logger.
- Defines the sendSms function.
- Performs validation, including checking E.164 format again.
- Constructs the payload for infobipClient.channels.sms.send.
- Includes logging for attempts and outcomes.
- Performs response checking based on status.groupName (e.g., 'PENDING', 'ACCEPTED') for better robustness.
- Throws detailed errors if the API call fails or indicates a non-successful submission status, extracting details from Infobip's error response if possible.
4. Implementing Scheduling Logic (node-cron)
We'll use node-cron to periodically check for due reminders and trigger the sending process.
- Create the Scheduler Job (
src/jobs/reminderScheduler.js):
const cron = require('node-cron');
const { findAndMarkDueReminders, updateReminderStatus } = require('../services/reminderService');
const { sendSms } = require('../services/smsService');
const logger = require('../config/logger');
const { Status } = require('@prisma/client');
let taskIsRunning = false;
const cronJob = cron.schedule('* * * * *', async () => {
const jobStartTime = Date.now();
logger.info(`[Cron Job] Running reminder check job...`);
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 β