Tutorials

Build a RedwoodJS App with Plivo Scheduled Reminders

A guide to building a full-stack RedwoodJS application for scheduling and sending SMS reminders using the Plivo API, covering setup, backend logic, database modeling, and deployment considerations.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 2, 2026 β€’ 13 min read

Developer Quick-Start: A guide to building a full-stack RedwoodJS application for scheduling and sending SMS reminders using the Plivo API, covering setup, backend logic, database modeling, and deployment considerations. 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 comprehensive walkthrough for building a full-stack application using RedwoodJS that enables users to schedule SMS reminders sent via Plivo. We'll cover everything from project setup and core logic implementation to deployment and best practices for a production-ready system.

By the end of this tutorial, you will have a functional web application where authenticated users can create, view, and delete reminders. A background process will periodically check for due reminders and use the Plivo API to dispatch them as SMS messages. This guide focuses heavily on the backend implementation details necessary for the scheduling and notification functionality.

Project Overview and Goals

What We're Building:

A multi-user web application where individuals can schedule SMS messages (reminders) to be sent to a specified phone number at a future date and time.

Problem Solved:

Automates the process of sending timely reminders via SMS, useful for appointments, tasks, events, or any time-sensitive notification. It provides a persistent, reliable mechanism managed through a web interface.

Technologies Used:

  • RedwoodJS: A full-stack JavaScript/TypeScript framework for the modern web. It provides structure for the API (GraphQL), web frontend (React), database access (Prisma), and simplifies setup, auth, and deployment. We use it for its integrated tooling and conventions.
  • Plivo: A Communications Platform as a Service (CPaaS). We use Plivo's SMS API to send the scheduled reminders. Its reliability and developer-friendly API make it a solid choice.
  • Node.js: The runtime environment for RedwoodJS's backend API layer where our scheduling and Plivo integration logic will reside.
  • Prisma: A next-generation Node.js and TypeScript ORM. RedwoodJS uses Prisma for database modeling, migrations, and type-safe database access.
  • PostgreSQL: A powerful, open-source object-relational database system. We'll use it to store user data and reminder schedules. (Other Prisma-compatible databases like MySQL or SQLite can also be used).
  • node-cron: A simple cron-like job scheduler for Node.js. We'll use this for demonstrating the scheduling mechanism within the Node.js process. Note: For production serverless deployments, an external scheduler (like Vercel Cron Jobs, AWS EventBridge Scheduler) is strongly recommended.

System Architecture:

+-------------+       +-------------------+       +-----------------+       +-------+
| User via    | ----> | RedwoodJS Frontend| ----> | RedwoodJS API   | ----> | Plivo |
| Web Browser |       | (React)           |       | (GraphQL, Node.js)|       | (SMS) |
+-------------+       +-------------------+       +--------+--------+       +-------+
                                                         |
                                                         |   +------------------+
                                                         +-> | PostgreSQL DB    |
                                                         |   | (Prisma)         |
                                                         |   +------------------+
                                                         |
                                                         |   +------------------+
                                                         +-> | Scheduling Logic |
                                                             | (`node-cron` or  |
                                                             | external trigger)|
                                                             +------------------+

(Note: Consider using a graphical diagram (SVG/PNG) for clearer presentation if your platform supports it.)

  1. A user interacts with the React frontend served by RedwoodJS.
  2. The frontend communicates with the RedwoodJS GraphQL API for actions like creating, fetching, or deleting reminders.
  3. The API uses Prisma services to interact with the PostgreSQL database, storing user and reminder information.
  4. Authentication ensures users can only manage their own reminders.
  5. A separate scheduling process (initially node-cron within the API, ideally an external trigger in production) runs periodically.
  6. The scheduler queries the database via Prisma for reminders due to be sent.
  7. For each due reminder, the API calls the Plivo SMS API to send the message.
  8. The reminder status is updated in the database.

Prerequisites:

  • Node.js: Version 20.x or higher recommended (check RedwoodJS docs for specific version compatibility). Use nvm to manage Node versions.
  • Yarn: Version 1.22.x or higher.
  • Plivo Account: Sign up for a Plivo account to get API credentials and a Plivo phone number capable of sending SMS.
  • Database: Access to a PostgreSQL database. We'll include steps for running one locally using Docker.
  • Git: (Recommended) For version control.
  • Basic understanding: JavaScript/TypeScript, React, GraphQL, and command-line usage.

Final Outcome:

A secure, authenticated RedwoodJS application enabling users to schedule and receive SMS reminders via Plivo, with a clear path to production deployment.

1. Setting up the Project

Let's initialize our RedwoodJS application and configure the essential tools.

  1. Create the RedwoodJS App: Open your terminal and run the create redwood-app command. We'll use TypeScript for enhanced type safety.
   yarn create redwood-app plivo-scheduler --typescript
  • Follow the prompts:
  • Initialize git repo? (Recommended: yes)
  • Enter commit message? (Initial commit)
  • Run yarn install? (yes)
  1. Navigate to Project Directory:
   cd plivo-scheduler
  1. Verify Node and Yarn Versions: Ensure your Node.js and Yarn versions meet the prerequisites mentioned earlier.
   node -v
   yarn -v
  1. Set up Local PostgreSQL Database (using Docker): If you don't have PostgreSQL running, Docker is a convenient way to start a local instance.
   docker pull postgres

   docker run --name plivo-scheduler-db -e POSTGRES_PASSWORD=your_postgres_password -d -p 5432:5432 postgres

   docker exec -it plivo-scheduler-db psql -U postgres
  • Explanation: This downloads the Postgres image and runs a container in detached mode (-d), mapping port 5432 on your host to the container's port 5432. It sets the default postgres user's password. We then use docker exec to run the psql command-line tool inside the container and execute the CREATE DATABASE command to set up the plivo\_scheduler database.
  1. Configure Environment Variables: RedwoodJS uses a .env file for environment variables. Create this file in the project root. Never commit .env files to Git. Add your database connection string.
   DATABASE_URL=postgresql://postgres:your_postgres_password@localhost:5432/plivo_scheduler?schema=public
  • Explanation: DATABASE\_URL tells Prisma how to connect to your database. Adjust the username, password, host, port, and database name if they differ from the Docker example. The ?schema=public part is often required. Quotes around the value are typically not needed unless the value contains special characters problematic for the shell.
  1. Initialize Prisma: Apply the initial database schema (which is currently empty besides Prisma's internal tracking).
   yarn rw prisma migrate dev --name initial-setup
  • Explanation: This command compares your schema.prisma file with the database, generates SQL migration files in api/db/migrations, and applies them to your database. The --name flag provides a descriptive name for the migration.
  1. Start the Development Server: Verify the basic setup works.
   yarn rw dev
  • Your browser should open to http://localhost:8910.
  • The API server runs on http://localhost:8911.
  • The GraphQL playground is accessible at http://localhost:8911/graphql.

Keep this running in a separate terminal tab during development.

2. Implementing Core Functionality (Scheduling Logic)

We'll store reminders in the database and use node-cron to check periodically for reminders that need sending.

  1. Install node-cron: Add the node-cron library to the API workspace.
   yarn workspace api add node-cron @types/node-cron --dev
  1. Define the Reminder Database Model: Edit the Prisma schema file (api/db/schema.prisma) to define the structure for storing reminders.

Prisma

   // api/db/schema.prisma

   datasource db {
     provider = ""postgresql""
     url      = env(""DATABASE_URL"")
   }

   generator client {
     provider      = ""prisma-client-js""
     binaryTargets = ""native""
   }

   // Define the Reminder model
   model Reminder {
     id                   Int      @id @default(autoincrement())
     message              String
     recipientPhoneNumber String   // Phone number to send the SMS to
     scheduledAt          DateTime // When the reminder should be sent (MUST be stored in UTC)
     status               String   @default(""PENDING"") // PENDING, SENT, FAILED
     createdAt            DateTime @default(now())
     updatedAt            DateTime @updatedAt
     userId               Int      // Foreign key to link to the User model
     user                 User     @relation(fields: [userId], references: [id])

     // Index optimized for the scheduler's primary query (finding pending/due reminders across all users)
     @@index([status, scheduledAt])
     // Index for efficient lookup of reminders by user (e.g., in the API)
     @@index([userId])
   }

   // Define the User model (basic example, add more fields as needed)
   model User {
     id                  Int        @id @default(autoincrement())
     email               String     @unique
     hashedPassword      String?
     salt                String?
     resetToken          String?
     resetTokenExpiresAt DateTime?
     reminders           Reminder[] // Relation to Reminders
     createdAt           DateTime   @default(now())
     updatedAt           DateTime   @updatedAt
   }
  • Explanation:
  • Reminder model stores the message content, recipient number, scheduled time (scheduledAt should always be stored in UTC), current status, and a link (userId) to the user who created it.
  • status: Tracks the lifecycle ('PENDING', 'SENT', 'FAILED').
  • userId / user: Creates a one-to-many relationship between User and Reminder.
  • @@index([status, scheduledAt]): Crucial index for scheduler performance. Allows the database to efficiently find rows matching status = 'PENDING' and scheduledAt <= now().
  • @@index([userId]): Supports efficient querying for reminders belonging to a specific user (e.g., in the API layer).
  • User model: Includes basic fields needed for authentication later (using Redwood's dbAuth).
  1. Apply Database Migrations: Generate and apply the migration for the new models.
   yarn rw prisma migrate dev --name add-reminder-and-user-models
  1. Create the Scheduler Service: This service (api/src/lib/scheduler.ts) will contain the logic to find and process due reminders.
   import cron from 'node-cron'
   import { db } from './db'
   import { logger } from './logger'
   import { sendSms } from './smsSender'

   const SCHEDULE = process.env.CRON_SCHEDULE || '*/1 * * * *'
   let isJobRunning = false

   logger.info(`Scheduler configured to run with schedule: ${SCHEDULE}`)

   cron.schedule(SCHEDULE, async () => {
     if (isJobRunning) {
       logger.warn('Previous scheduler job still running, skipping this run.')
       return
     }

     isJobRunning = true
     logger.info('Scheduler job started: Checking for due reminders...')

     try {




       const now = new Date()


       const dueReminders = await db.reminder.findMany({
         where: {
           status: 'PENDING',
           scheduledAt: {
             lte: now,
           },
         },
         include: {
           user: true,
         },

         take: parseInt(process.env.SCHEDULER_BATCH_SIZE || '50', 10),
       })

       logger.info(`Found ${dueReminders.length} due reminders.`)

       if (dueReminders.length === 0) {
         logger.info('No due reminders to process.')
         isJobRunning = false
         return
       }


       for (const reminder of dueReminders) {
         try {
           logger.info(`Processing reminder ID: ${reminder.id} for user ${reminder.userId}`)


           const plivoResponse = await sendSms(
             reminder.recipientPhoneNumber,
             reminder.message
           )



           if (plivoResponse && plivoResponse.messageUuid) {
             await db.reminder.update({
               where: { id: reminder.id },
               data: { status: 'SENT' },
             })
             logger.info(`Successfully sent reminder ID: ${reminder.id}, Plivo Message UUID: ${plivoResponse.messageUuid}`)
           } else {

             throw new Error('Plivo SMS sending failed or did not return expected response.')
           }

         } catch (error: any) {

           logger.error(
             `Failed to process reminder ID: ${reminder.id}. Error: ${error.message}`
           )
           await db.reminder.update({
             where: { id: reminder.id },
             data: { status: 'FAILED' },
           })
         }
       }

       logger.info('Finished processing batch of reminders.')

     } catch (error: any) {
       logger.error(`Error during scheduler run: ${error.message}`, error.stack)
     } finally {
       isJobRunning = false
       logger.info('Scheduler job finished.')
     }
   }, {
     scheduled: true,





   })

   logger.info('Cron job scheduled.')

   export const stopScheduler = () => {

     cron.getTasks().forEach(task => task.stop());
     logger.info('Scheduler stopped.')
   }
  • Explanation:
  • Imports node-cron, Prisma (db), logger, and the sendSms function (to be created).
  • Defines a SCHEDULE (defaulting to every minute). Configurable via .env.
  • Uses a simple isJobRunning flag as a lock to prevent the job from running concurrently if a previous run takes too long.
  • cron.schedule sets up the job.
  • Inside the job:
  • Timezone Critical: Queries the DB for PENDING reminders where scheduledAt (UTC) is less than or equal to the current time (now). It's crucial the server runs in UTC so new Date() reflects UTC, ensuring accurate comparison.
  • Uses take to process reminders in batches (configurable via SCHEDULER\_BATCH\_SIZE).
  • Loops through due reminders.
  • Calls sendSms.
  • Updates the status to SENT on success or FAILED on error using db.reminder.update.
  • Includes robust logging and error handling using try...catch.
  • The finally block ensures the isJobRunning lock is always released.
  • Adds a note reinforcing the importance of UTC for the server environment.
  1. Start the Scheduler: The scheduler needs to be initialized when the API server starts. A common place in Redwood is within the server configuration or alongside the db client initialization, ensuring it runs once. Let's modify the db client setup file (api/src/lib/db.ts).
   import { logger } from './logger'

   import { PrismaClient } from '@prisma/client'
   export const db = new PrismaClient({
     log: process.env.NODE_ENV === 'development' ? ['query', 'info', 'warn', 'error'] : ['error'],
   })

   if (process.env.NODE_ENV !== 'test' && process.env.DISABLE_SCHEDULER !== 'true') {
     logger.info('Initializing node-cron scheduler for serverful/dev environment...')
     import('./scheduler').catch(err => {
       logger.error('Failed to load node-cron scheduler:', err)
     })
   } else if (process.env.DISABLE_SCHEDULER === 'true'){
       logger.warn('Scheduler explicitly disabled via DISABLE_SCHEDULER env var.')
   } else {
      logger.info('Scheduler disabled in test environment.')
   }
  • Explanation:
  • We import the ./scheduler file after the db client is potentially initialized. The dynamic import() ensures it runs.
  • We add checks (process.env.NODE\_ENV !== 'test', process.env.DISABLE\_SCHEDULER !== 'true') to prevent the scheduler from running during tests or if explicitly disabled via an environment variable.
  • Crucially, a prominent warning explains this node-cron initialization method is unsuitable for serverless and directs the user to the Deployment section for the correct approach using external triggers.

3. Building the API Layer (GraphQL)

We'll use Redwood's generators to create the GraphQL schema definition (SDL) and service implementations for managing reminders.

  1. Set up Authentication: Reminders should be user-specific. We'll use Redwood's built-in dbAuth.
   yarn rw setup auth dbAuth
  • This command modifies files to integrate database-backed authentication:
  • Adds required fields (hashedPassword, salt, etc.) to the User model in schema.prisma (we already added them, but it ensures they're standard).
  • Generates API functions (api/src/functions/auth.ts).
  • Generates auth service (api/src/services/auth.ts).
  • Adds frontend pages for login, signup, etc. (web/src/pages/LoginPage, web/src/pages/SignupPage, etc.).
  • Sets up the AuthContext (web/src/auth.ts).
  • Important: After running yarn rw setup auth dbAuth, if you hadn't already manually added the necessary fields (hashedPassword, salt, etc.) to your User model in schema.prisma (as we did in our example), you must run a database migration to add them:
     yarn rw prisma migrate dev --name setup-dbAuth
  1. Generate SDL and Services for Reminder:
   yarn rw g sdl Reminder --crud
  • Explanation: This command inspects your Reminder model in schema.prisma and generates:
  • api/src/graphql/reminders.sdl.ts: Defines the GraphQL schema types (Reminder, CreateReminderInput, UpdateReminderInput) and CRUD operations (queries like reminders, reminder, and mutations like createReminder, updateReminder, deleteReminder).
  • api/src/services/reminders/reminders.ts: Implements the resolver functions for the generated SDL operations, interacting with the database via Prisma.
  • api/src/services/reminders/reminders.scenarios.ts: Seed data for testing.
  • api/src/services/reminders/reminders.test.ts: Basic test structure.
  1. Secure the Reminder Service: Modify the generated service file (api/src/services/reminders/reminders.ts) to ensure users can only access and manage their own reminders. Use Redwood's requireAuth utility and filter queries/mutations by the current user's ID.
   import type { QueryResolvers, MutationResolvers, ReminderRelationResolvers } from 'types/graphql'
   import { RedwoodGraphQLError, ForbiddenError } from '@redwoodjs/graphql-server'
   import { db } from 'src/lib/db'
   import { requireAuth } from 'src/lib/auth'

   export const reminders: QueryResolvers['reminders'] = () => {
     requireAuth()
     return db.reminder.findMany({
       where: { userId: context.currentUser?.id },
       orderBy: { scheduledAt: 'asc' }
     })
   }

   export const reminder: QueryResolvers['reminder'] = async ({ id }) => {
     requireAuth()
     const reminder = await db.reminder.findFirst({
       where: { id, userId: context.currentUser?.id },
     })
     if (!reminder) {
       throw new RedwoodGraphQLError('Reminder not found.')
     }
     return reminder
   }

   export const createReminder: MutationResolvers['createReminder'] = ({ input }) => {
     requireAuth()



     return db.reminder.create({
       data: {
         ...input,
         userId: context.currentUser?.id,
         status: 'PENDING',
       },
     })
   }

   export const updateReminder: MutationResolvers['updateReminder'] = async ({ id, input }) => {
     requireAuth()

     const existingReminder = await db.reminder.findFirst({
       where: { id, userId: context.currentUser?.id },
     })

     if (!existingReminder) {
       throw new RedwoodGraphQLError('Reminder not found or you do not have permission to update it.')
     }



     if (existingReminder.status !== 'PENDING') {
         throw new RedwoodGraphQLError(`Cannot update a reminder with status: ${existingReminder.status}`)
     }

     return db.reminder.update({
       data: input,
       where: { id },
     })
   }

   export const deleteReminder: MutationResolvers['deleteReminder'] = async ({ id }) => {
     requireAuth()

     const existingReminder = await db.reminder.findFirst({
       where: { id, userId: context.currentUser?.id },
     })

     if (!existingReminder) {
       throw new RedwoodGraphQLError('Reminder not found or you do not have permission to delete it.')
     }

     return db.reminder.delete({
       where: { id },
     })
   }

   export const Reminder: ReminderRelationResolvers = {
     user: (_obj, { root }) => {
       return db.reminder.findUnique({ where: { id: root?.id } }).user()
     },
   }
  • Explanation:
  • requireAuth(): This function (provided by yarn rw setup auth dbAuth) checks if a user is logged in (context.currentUser is set). If not, it throws an AuthenticationError.
  • where: { userId: context.currentUser?.id }: This clause is added to findMany, findFirst, update, and delete operations (or checks preceding them) to ensure actions only affect reminders belonging to the currently authenticated user.
  • RedwoodGraphQLError: Used for user-facing errors like ""Reminder not found.""
  • Added a check in updateReminder to prevent updating non-pending reminders (example of business logic).
  1. Testing API Endpoints (Example using GraphQL Playground):
  • Start the dev server: yarn rw dev
  • Sign up and log in through the frontend UI (e.g., http://localhost:8910/signup, http://localhost:8910/login).
  • Open the GraphQL Playground: http://localhost:8911/graphql
  • The Playground usually handles authentication cookies automatically after you log in via the frontend on the same localhost domain. If not, you might need to manually copy authentication headers/tokens.
  • Create Reminder Mutation:
     mutation CreateReminderMutation($input: CreateReminderInput!) {
       createReminder(input: $input) {
         id
         message
         recipientPhoneNumber
         scheduledAt
         status
         userId
       }
     }

Variables:

     {
       ""input"": {
         ""message"": ""Test reminder from GraphQL Playground"",
         ""recipientPhoneNumber"": ""+15551234567"",
         ""scheduledAt"": ""2025-12-01T10:00:00.000Z""
       }
     }

(Replace phone number and use a future UTC date/time) Expected Response (JSON):

     {
       ""data"": {
         ""createReminder"": {
           ""id"": 1,
           ""message"": ""Test reminder from GraphQL Playground"",
           ""recipientPhoneNumber"": ""+15551234567"",
           ""scheduledAt"": ""2025-12-01T10:00:00.000Z"",
           ""status"": ""PENDING"",
           ""userId"": 1
         }
       }
     }
  • Get Reminders Query:
     query GetRemindersQuery {
       reminders {
         id
         message
         scheduledAt
         status
       }
     }

Expected Response (JSON):

     {
       ""data"": {
         ""reminders"": [
           {
             ""id"": 1,
             ""message"": ""Test reminder from GraphQL Playground"",
             ""scheduledAt"": ""2025-12-01T10:00:00.000Z"",
             ""status"": ""PENDING""
           }

         ]
       }
     }
  • Test updateReminder and deleteReminder similarly, ensuring you use the ID of a reminder created by the logged-in user.

4. Integrating with Plivo

Now, let's connect our application to Plivo to actually send the SMS messages.

  1. Obtain Plivo Credentials and Phone Number:
  • Log in to your Plivo Console (dashboard).
  • Navigate to Settings > API Credentials. Note your Auth ID and Auth Token.
  • Navigate to Phone Numbers > Your Numbers. Ensure you have an SMS-enabled Plivo phone number. Note the Number. If you don't have one, purchase one that supports SMS in your desired region.
  1. Store Credentials Securely: Add your Plivo credentials and sender number to the .env file. Do not commit this file.
   DATABASE_URL=postgresql://postgres:your_postgres_password@localhost:5432/plivo_scheduler?schema=public

   PLIVO_AUTH_ID=""YOUR_PLIVO_AUTH_ID""
   PLIVO_AUTH_TOKEN=""YOUR_PLIVO_AUTH_TOKEN""
   PLIVO_SENDER_NUMBER=""+1YOURPLIVONUMBER""
  • Explanation: These environment variables will be used by our Plivo client setup. PLIVO\_SENDER\_NUMBER must be in E.164 format (e.g., +15551234567). We also added CRON\_TRIGGER\_SECRET for later use in serverless deployments.
  1. Install Plivo Node.js SDK: Add the official Plivo SDK to the API workspace.
   yarn workspace api add plivo
  1. Create Plivo Client Utility: Create a file (api/src/lib/plivoClient.ts) to initialize and export the Plivo client instance.
   import * as plivo from 'plivo'
   import { logger } from './logger'

   const authId = process.env.PLIVO_AUTH_ID
   const authToken = process.env.PLIVO_AUTH_TOKEN

   if (!authId || !authToken) {
     logger.error('Plivo Auth ID or Auth Token missing in environment variables.')


   }

   export const plivoClient =
     authId && authToken ? new plivo.Client(authId, authToken) : null

   if (plivoClient) {
     logger.info('Plivo client initialized successfully.')
   } else {
     logger.warn('Plivo client not initialized due to missing credentials.')
   }

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 β†’