Developer Quick-Start: A guide to building a full-stack application for scheduling and sending SMS reminders using RedwoodJS, Infobip, Node.js, 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 complete walkthrough for building a robust application that schedules and sends SMS reminders using RedwoodJS for the full-stack framework, Infobip for SMS delivery, and Node.js features for scheduling. We'll cover everything from initial setup to deployment and monitoring.
By the end of this tutorial, you will have a functional web application where users can schedule appointments (or any event), and the system will automatically send an SMS reminder via Infobip at the specified time, respecting time zones. This solves the common business problem of needing automated, reliable communication for appointments, notifications, or alerts, helping reduce no-shows and improve user engagement.
Project Overview and Goals
We aim to build a full-stack application with the following capabilities:
- Web Interface: A frontend built with RedwoodJS (React) to create, view, and manage scheduled SMS messages (appointments).
- API Backend: A RedwoodJS API (GraphQL) to handle data persistence (using Prisma and PostgreSQL) and interact with the scheduling and SMS sending logic.
- SMS Sending: Integration with the Infobip SMS API using their official Node.js SDK to dispatch messages.
- Scheduling: A reliable mechanism using node-cron running on the Node.js backend to trigger SMS sending at the correct time, accounting for different time zones.
- Persistence: Storing appointment details, recipient information, and status in a PostgreSQL database via Prisma.
Technologies:
- RedwoodJS: A full-stack JavaScript/TypeScript framework for the web. Chosen for its integrated frontend (React) and backend (GraphQL API, Prisma), conventions, and developer experience features (generators, cells, etc.).
- Node.js: The runtime environment for the RedwoodJS backend and scheduling logic.
- Infobip: A communications platform-as-a-service (CPaaS) provider. Chosen for its robust SMS API and Node.js SDK.
- Prisma: A next-generation ORM for Node.js and TypeScript. RedwoodJS's default ORM, simplifying database interactions.
- PostgreSQL: A powerful, open-source relational database.
node-cron: A simple cron-like job scheduler for Node.js. Chosen for its simplicity in scheduling tasks within the Node.js process.- TypeScript: For type safety and improved maintainability.
System Architecture:
graph LR
A[User Browser] -- HTTPS --> B(RedwoodJS Web Frontend);
B -- GraphQL API Call --> C(RedwoodJS API Backend);
C -- Prisma Client --> D[(PostgreSQL DB)];
C -- Schedules Job --> E(Node-Cron Scheduler);
E -- Triggers at Scheduled Time --> C;
C -- Infobip SDK --> F(Infobip SMS API);
F -- Sends SMS --> G(User's Phone);
subgraph RedwoodJS App
direction LR
B
C
E
end
Prerequisites:
- Node.js (v20 or higher recommended, check RedwoodJS docs for specifics)
- Yarn (v1.22.21 or higher)
- An Infobip Account (Sign up at Infobip)
- Access to a PostgreSQL database (local or cloud-hosted)
- Basic familiarity with JavaScript/TypeScript, React, GraphQL, and terminal commands.
1. Setting up the Project
Let's initialize our RedwoodJS project and install necessary dependencies.
- Verify Node/Yarn Versions: Open your terminal and check your versions:
node -v
yarn -v
If needed, update Node.js (using nvm is recommended:
nvm install 20 && nvm use 20) and Yarn (npm install -g yarn).
- Create RedwoodJS App: Use the
create-redwood-appcommand. We'll use TypeScript (default) and initialize a git repo.
yarn create redwood-app redwood-infobip-scheduler --typescript --git-init
Follow the prompts (commit message, yarn install).
- Navigate to Project Directory:
cd redwood-infobip-scheduler
- Configure Database Connection: Locate the
.envfile in the project root. Update theDATABASE_URLvariable to point to your PostgreSQL database. Ensure the quotes are correct. Example for a local setup:
DATABASE_URL=""postgresql://postgres:password@localhost:5432/schedulerdb?schema=public""
Replace postgres, password, localhost, 5432, and
schedulerdb with your actual database credentials and name.
- Install Dependencies: We need the Infobip SDK,
node-cronfor scheduling,date-fns-tzfor robust timezone handling, and type definitions.
yarn workspace api add @infobip-api/sdk node-cron date-fns-tz
yarn workspace api add -D @types/node-cron
- @infobip-api/sdk: The official SDK for interacting with Infobip APIs.
- node-cron: To schedule the SMS sending tasks.
- date-fns-tz: For accurate timezone conversions, essential for reliable scheduling.
- @types/node-cron: TypeScript definitions for node-cron.
- Configure Infobip Credentials: Add your Infobip API Key and Base URL to the
.envfile. You can find these in your Infobip account dashboard under API Keys. Also, define a sender ID (optional, but recommended).
- How to find Infobip Credentials:
- Log in to your Infobip account.
- Navigate to the ""Developers"" or ""API Keys"" section (this might vary slightly based on UI updates).
- Generate or copy an existing API Key.
- Note down your unique Base URL (e.g., xxxxx.api.infobip.com).
Add the following lines to your .env file:
INFOBIP_API_KEY=""YOUR_INFOBIP_API_KEY""
INFOBIP_BASE_URL=""YOUR_INFOBIP_BASE_URL""
INFOBIP_SENDER_ID=""InfoSMS""
Important: Replace YOUR_INFOBIP_API_KEY and YOUR_INFOBIP_BASE_URL
with the actual credentials obtained from your Infobip account. These are sensitive secrets.
Security Note: Never commit your .env file to version control. Ensure
.env is listed in your .gitignore file (it should be by default in RedwoodJS).
- Initial Commit (if not done during setup):
git add .
git commit -m ""Initial project setup with dependencies""
2. Database Schema and Data Layer
We need a database table to store information about the appointments or scheduled messages.
- Define Prisma Schema: Open
api/db/schema.prismaand define theAppointmentmodel.
Prisma
// api/db/schema.prisma
datasource db {
provider = ""postgresql""
url = env(""DATABASE_URL"")
}
generator client {
provider = ""prisma-client-js""
binaryTargets = ""native""
}
model Appointment {
id Int @id @default(autoincrement())
recipientName String?
recipientPhone String // E.164 format recommended (e.g., +14155552671)
message String
scheduledAt DateTime // Store time in UTC
timeZone String // IANA Time Zone Name (e.g., ""America/New_York"")
status String @default(""PENDING"") // PENDING, SENT, FAILED
infobipMessageId String? // Store Infobip's message ID after sending
failureReason String? // Store reason if sending failed
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([status, scheduledAt]) // Index for finding pending future jobs
}
- recipientPhone: The destination phone number. Using E.164 format is crucial for international compatibility.
- scheduledAt: The date and time in UTC when the reminder should be sent.
- timeZone: The recipient's local time zone (IANA format). This is critical for scheduling the job correctly.
- status: Tracks the state of the reminder.
- infobipMessageId: Useful for tracking delivery status via Infobip later.
- failureReason: Optional field to store error messages if sending fails.
- Added @@index([status, scheduledAt]) for query performance.
- Create and Apply Migration: Run the following command to generate the SQL migration file and apply it to your development database:
yarn rw prisma migrate dev
When prompted, provide a name for the migration (e.g., create_appointment_model). This command
also generates/updates the Prisma Client based on your schema.
3. Core Functionality - API Layer
Now, let's build the backend logic: API endpoints for managing appointments, integrating with Infobip, and setting up the scheduler.
- Generate GraphQL SDL and Service: Redwood's generators make this easy.
yarn rw g sdl Appointment
This creates:
- api/src/graphql/appointments.sdl.ts: Defines the GraphQL schema (types, queries, mutations).
- api/src/services/appointments/appointments.ts: Implements the resolvers (business logic) for the SDL.
- api/src/services/appointments/appointments.scenarios.ts: For seeding test data.
- api/src/services/appointments/appointments.test.ts: Unit test file.
- Implement CRUD Operations: Open
api/src/services/appointments/appointments.tsand implement the basic CRUD functions.
import type { QueryResolvers, MutationResolvers } from 'types/graphql'
import { db } from 'src/lib/db'
import { scheduleAppointmentJob, cancelScheduledJob } from 'src/lib/scheduler'
import { requireAuth } from 'src/lib/auth'
export const appointments: QueryResolvers['appointments'] = () => {
return db.appointment.findMany({ orderBy: { scheduledAt: 'asc' } })
}
export const appointment: QueryResolvers['appointment'] = ({ id }) => {
return db.appointment.findUnique({
where: { id },
})
}
export const createAppointment: MutationResolvers['createAppointment'] = async ({ input }) => {
if (!input.recipientPhone || !input.message || !input.scheduledAt || !input.timeZone) {
throw new Error('Missing required appointment fields.')
}
const phoneRegex = /^\+[1-9]\d{1,14}$/;
if (!phoneRegex.test(input.recipientPhone)) {
throw new Error('Invalid phone number format. Use E.164 (e.g., +14155552671).');
}
const scheduledAtUTC = new Date(input.scheduledAt);
if (isNaN(scheduledAtUTC.getTime())) {
throw new Error('Invalid scheduled date/time format.');
}
const newAppointment = await db.appointment.create({
data: {
...input,
scheduledAt: scheduledAtUTC,
status: 'PENDING',
failureReason: null,
},
})
try {
await scheduleAppointmentJob(newAppointment);
} catch (scheduleError) {
await db.appointment.update({
where: { id: newAppointment.id },
data: { status: 'FAILED', failureReason: `Scheduling failed: ${scheduleError.message}` }
});
throw scheduleError;
}
return newAppointment
}
export const updateAppointment: MutationResolvers['updateAppointment'] = async ({ id, input }) => {
const existingAppointment = await db.appointment.findUnique({ where: { id } });
if (!existingAppointment) {
throw new Error(`Appointment with ID ${id} not found.`);
}
if (input.recipientPhone && !/^\+[1-9]\d{1,14}$/.test(input.recipientPhone)) {
throw new Error('Invalid phone number format. Use E.164 (e.g., +14155552671).');
}
if (input.scheduledAt && isNaN(new Date(input.scheduledAt).getTime())) {
throw new Error('Invalid scheduled date/time format.');
}
await cancelScheduledJob(existingAppointment.id);
const updatedAppointment = await db.appointment.update({
data: {
...input,
scheduledAt: input.scheduledAt ? new Date(input.scheduledAt) : undefined,
failureReason: null,
status: existingAppointment.status === 'FAILED' ? 'PENDING' : existingAppointment.status,
},
where: { id },
})
if (updatedAppointment.status === 'PENDING') {
try {
await scheduleAppointmentJob(updatedAppointment);
} catch (scheduleError) {
await db.appointment.update({
where: { id: updatedAppointment.id },
data: { status: 'FAILED', failureReason: `Rescheduling failed: ${scheduleError.message}` }
});
throw scheduleError;
}
}
return updatedAppointment
}
export const deleteAppointment: MutationResolvers['deleteAppointment'] = async ({ id }) => {
const existingAppointment = await db.appointment.findUnique({ where: { id } });
if (!existingAppointment) {
throw new Error(`Appointment with ID ${id} not found.`);
}
await cancelScheduledJob(existingAppointment.id);
return db.appointment.delete({
where: { id },
})
}
- Added comments emphasizing backend validation in createAppointment and updateAppointment.
- Included basic E.164 validation example.
- Added try...catch around scheduleAppointmentJob calls to handle potential scheduling errors during create/update.
- Added requireAuth() comments as placeholders (uncomment/implement if auth is set up).
- Initialized/reset failureReason.
- Implement Infobip Integration: Create/update the utility file for Infobip interactions.
import { Infobip, AuthType } from '@infobip-api/sdk'
import { logger } from 'src/lib/logger'
const apiKey = process.env.INFOBIP_API_KEY
const baseUrl = process.env.INFOBIP_BASE_URL
if (!apiKey || !baseUrl) {
logger.error('Infobip API Key or Base URL not configured in .env file. SMS sending will fail.')
}
let infobipClient: Infobip | null = null;
if (apiKey && baseUrl) {
infobipClient = new Infobip({
baseUrl: baseUrl,
apiKey: apiKey,
authType: AuthType.ApiKey,
});
} else {
logger.warn('Infobip client not initialized due to missing credentials.');
}
export const sendSms = async (to: string, text: string): Promise<{ success: boolean; messageId?: string; error?: string }> => {
if (!infobipClient) {
const errorMsg = 'Infobip client is not initialized. Check API Key/Base URL configuration.';
logger.error(errorMsg);
return { success: false, error: errorMsg };
}
const sender = process.env.INFOBIP_SENDER_ID || 'RedwoodApp'
if (!to || !text) {
const errorMsg = 'Missing recipient phone or message text for SMS.';
logger.error(errorMsg)
return { success: false, error: errorMsg }
}
if (!/^\+[1-9]\d{1,14}$/.test(to)) {
const errorMsg = `Invalid recipient phone format: ${to}. Use E.164.`;
logger.error(errorMsg);
return { success: false, error: errorMsg };
}
logger.info(`Attempting to send SMS via Infobip to ${to}`)
try {
const response = await infobipClient.channels.sms.send({
messages: [
{
destinations: [{ to }],
from: sender,
text: text,
},
],
})
const messageResponse = response.data.messages?.[0]
if (messageResponse?.status?.groupName === 'PENDING' || messageResponse?.status?.groupName === 'DELIVERED') {
logger.info(`Infobip accepted SMS: ${messageResponse.messageId}, Status: ${messageResponse.status.name} (${messageResponse.status.groupName})`)
return { success: true, messageId: messageResponse.messageId }
} else {
const errorText = messageResponse?.status?.description || `Status: ${messageResponse?.status?.name ?? 'Unknown'}, Group: ${messageResponse?.status?.groupName ?? 'Unknown'}`;
logger.error({ infobipResponse: response.data }, `Infobip SMS sending failed or status not PENDING/DELIVERED. ${errorText}`)
return { success: false, error: `Infobip error: ${errorText}` }
}
} catch (error) {
logger.error({ error: error?.response?.data || error.message }, 'Error sending SMS via Infobip SDK')
let errorMessage = 'Unknown Infobip SDK error';
if (error.response?.data?.requestError?.serviceException?.text) {
errorMessage = `Infobip API Error: ${error.response.data.requestError.serviceException.text}`;
} else if (error.message) {
errorMessage = error.message;
} else if (typeof error.response?.data === 'string') {
errorMessage = `Infobip API Error: ${error.response.data}`;
}
return { success: false, error: errorMessage }
}
}
- Handles missing credentials more gracefully (logs warning, prevents client init).
- Checks for client initialization before sending.
- Improved error message extraction from Infobip responses.
- Implement Scheduling Logic: Create/update the file for the
node-cronscheduler, incorporating robust timezone handling and clarifying persistence limitations.
import cron from 'node-cron'
import { db } from 'src/lib/db'
import { logger } from 'src/lib/logger'
import { sendSms } from './infobip'
import type { Appointment } from '@prisma/client'
import { formatInTimeZone, zonedTimeToUtc } from 'date-fns-tz'
const scheduledJobs = new Map<number, cron.ScheduledTask>();
const getCronPattern = (dateUtc: Date, timeZone: string): string => {
try {
const minute = formatInTimeZone(dateUtc, timeZone, 'm');
const hour = formatInTimeZone(dateUtc, timeZone, 'H');
const dayOfMonth = formatInTimeZone(dateUtc, timeZone, 'd');
const month = formatInTimeZone(dateUtc, timeZone, 'M');
const dayOfWeek = '*';
const pattern = `${minute} ${hour} ${dayOfMonth} ${month} ${dayOfWeek}`;
logger.info(`Generated cron pattern: ${pattern} for date ${dateUtc.toISOString()} in target TZ ${timeZone}`);
return pattern;
} catch (error) {
logger.error({ error, dateUtc, timeZone }, `Failed to generate cron pattern using date-fns-tz. Invalid timezone?`);
throw new Error(`Invalid timezone or date for pattern generation: ${timeZone}`);
}
}
const executeJob = async (appointment: Appointment) => {
logger.info(`Executing job for Appointment ID: ${appointment.id} to ${appointment.recipientPhone}`);
const currentAppointment = await db.appointment.findUnique({ where: { id: appointment.id } });
if (!currentAppointment) {
logger.warn(`Job execution skipped: Appointment ID ${appointment.id} not found.`);
cancelScheduledJob(appointment.id);
return;
}
if (currentAppointment.status !== 'PENDING') {
logger.warn(`Job execution skipped for Appointment ID: ${appointment.id}. Status is ${currentAppointment.status}, not PENDING.`);
cancelScheduledJob(appointment.id);
return;
}
const result = await sendSms(currentAppointment.recipientPhone, currentAppointment.message);
const newStatus = result.success ? 'SENT' : 'FAILED';
const failureReason = result.success ? null : (result.error || 'Unknown Infobip sending error');
await db.appointment.update({
where: { id: appointment.id },
data: {
status: newStatus,
infobipMessageId: result.messageId,
failureReason: failureReason,
},
});
logger.info(`Job finished for Appointment ID: ${appointment.id}. Status updated to ${newStatus}. Infobip Msg ID: ${result.messageId ?? 'N/A'}`);
cancelScheduledJob(appointment.id);
}
export const scheduleAppointmentJob = async (appointment: Appointment) => {
if (appointment.status !== 'PENDING') {
logger.info(`Skipping scheduling for Appointment ID: ${appointment.id}. Status: ${appointment.status}`);
return;
}
const scheduledAtUTC = new Date(appointment.scheduledAt);
if (scheduledAtUTC <= new Date()) {
logger.warn(`Skipping scheduling for Appointment ID: ${appointment.id}. Scheduled time is in the past.`);
await db.appointment.update({
where: { id: appointment.id },
data: { status: 'FAILED', failureReason: 'Scheduled time is in the past.' }
});
return;
}
await cancelScheduledJob(appointment.id);
try {
const cronPattern = getCronPattern(scheduledAtUTC, appointment.timeZone);
const task = cron.schedule(cronPattern, async () => {
try {
await executeJob(appointment);
} catch (error) {
logger.error({ error, appointmentId: appointment.id }, 'Unhandled error during job execution wrapper');
try {
await db.appointment.update({
where: { id: appointment.id },
data: { status: 'FAILED', failureReason: `Job execution error: ${error.message}` },
});
} catch (updateError) {
logger.error({ updateError, appointmentId: appointment.id }, 'Failed to update status after job execution error');
}
cancelScheduledJob(appointment.id);
}
}, {
scheduled: true,
});
scheduledJobs.set(appointment.id, task);
logger.info(`Scheduled job for Appointment ID: ${appointment.id} with pattern ""${cronPattern}"" for target TZ ${appointment.timeZone}`);
} catch (error) {
logger.error({ error, appointmentId: appointment.id }, 'Failed to schedule cron job');
await db.appointment.update({
where: { id: appointment.id },
data: { status: 'FAILED', failureReason: `Failed to schedule: ${error.message}` }
});
throw error;
}
}
export const cancelScheduledJob = async (appointmentId: number) => {
if (scheduledJobs.has(appointmentId)) {
logger.info(`Cancelling job for Appointment ID: ${appointmentId}`);
scheduledJobs.get(appointmentId)?.stop();
scheduledJobs.delete(appointmentId);
}
}
export const initializeScheduler = async () => {
logger.info('Initializing scheduler: Loading pending jobs from database...');
scheduledJobs.forEach(job => job.stop());
scheduledJobs.clear();
const pendingAppointments = await db.appointment.findMany({
where: {
status: 'PENDING',
scheduledAt: {
gt: new Date(),
},
},
});
logger.info(`Found ${pendingAppointments.length} pending appointments to re-schedule.`);
let successCount = 0;
let failureCount = 0;
for (const appointment of pendingAppointments) {
try {
await scheduleAppointmentJob(appointment);
successCount++;
} catch (error) {
logger.error({ error, appointmentId: appointment.id }, `Failed to re-schedule job during initialization`);
failureCount++;
}
}
logger.info(`Scheduler initialization complete. Successfully scheduled: ${successCount}, Failed: ${failureCount}.`);
}
- Added date-fns-tz import and used it in getCronPattern for robust timezone handling.
- Removed the potentially ambiguous timezone option from cron.schedule.
- Strengthened the warning about the in-memory scheduledJobs map and its limitations, mentioning persistent queues earlier.
- Improved the comments regarding where and why initializeScheduler must be called, strongly advising against the GraphQL context and recommending api/src/server.ts or similar startup hooks. Added a conceptual example.
- Added error handling within initializeScheduler loop.
- executeJob now refetches the appointment for latest status.
4. Building the Frontend
Let's create the UI for managing appointments using RedwoodJS Cells and Forms.
- Generate Page and Cell:
yarn rw g page Appointments /appointments
yarn rw g cell Appointments
This creates:
- web/src/pages/AppointmentsPage/AppointmentsPage.tsx
- web/src/components/AppointmentsCell/AppointmentsCell.{tsx,mock.ts,test.tsx}
- Implement AppointmentsCell: Edit
web/src/components/AppointmentsCell/AppointmentsCell.tsx.
import type { AppointmentsQuery, AppointmentsQueryVariables } from 'types/graphql'
import type { CellSuccessProps, CellFailureProps } from '@redwoodjs/web'
import AppointmentForm from 'src/components/AppointmentForm/AppointmentForm'
export const QUERY = gql`
query AppointmentsQuery {
appointments {
id
recipientName
recipientPhone
message
scheduledAt
timeZone
status
failureReason
createdAt
infobipMessageId
}
}
`
export const Loading = () => <div>Loading appointments...</div>
export const Empty = () => (
<div>
<h2>No appointments scheduled yet.</h2>
<AppointmentForm />
</div>
)
export const Failure = ({ error }: CellFailureProps<AppointmentsQueryVariables>) => (
<div style={{ color: 'red' }}>Error loading appointments: {error?.message}</div>
)
export const Success = ({ appointments, refetch }: CellSuccessProps<AppointmentsQuery, AppointmentsQueryVariables>) => {
return (
<div>
<h2>Scheduled Appointments</h2>
{/* Add a refetch button maybe? */}
{/* Add table or list display of appointments here */}
{/* Add AppointmentForm for creating new ones */}
{/* Example: <AppointmentForm onSuccess={refetch} /> */}
{/* Example: <AppointmentsList appointments={appointments} onDelete={refetch} onUpdate={refetch} /> */}
</div>
)
}
- Added failureReason and infobipMessageId to the QUERY.
- Included placeholder comments in the Success component for where the list/table and form would go.
- Note: The full implementation of the list display and integration with AppointmentForm (which would need to be created separately, likely with yarn rw g component AppointmentForm) is beyond the scope of this snippet but would be the next step here.
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 β