Tutorials

Building Production-Ready SMS Scheduling & Reminders with Fastify and Infobip

A guide on creating a production-ready SMS scheduling and reminder system using Fastify, Infobip, Prisma, and Node.js, covering setup, implementation, and best practices.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 5, 2026 β€’ 14 min read

Developer Quick-Start: A guide on creating a production-ready SMS scheduling and reminder system using Fastify, Infobip, Prisma, and Node.js, covering setup, implementation, and best practices. 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 SMS scheduling and reminder system using the Fastify web framework for Node.js and the Infobip communications platform. We will cover everything from project setup to deployment, focusing on production-readiness, best practices, and real-world considerations.

By the end of this tutorial, you will have a functional application capable of:

  • Scheduling SMS messages to be sent at a specific future time.
  • Retrieving details of scheduled messages.
  • Rescheduling messages to a new time.
  • Checking the status of scheduled messages (e.g., PENDING, CANCELED).
  • Canceling scheduled messages before they are sent.
  • Storing and managing scheduled job metadata in a database.

This system solves the common business need for automated, timed communication like appointment reminders, payment due date notifications, event follow-ups, and abandoned cart recovery messages, helping to reduce no-shows, improve engagement, and save manual effort.

Project Overview and Goals

We aim to build a backend service using Fastify that exposes a RESTful API for managing scheduled SMS messages via Infobip.

Technologies Used:

  • Node.js: The runtime environment for our JavaScript backend (ES Module syntax).
  • Fastify: A high-performance, low-overhead web framework for Node.js, chosen for its speed, extensibility, and developer-friendly features (like built-in validation and logging).
  • Infobip API: The third-party service used for sending and managing SMS messages. Chosen for its global reach, reliability, and specific features for scheduling and managing bulk messages.
  • Axios: A promise-based HTTP client for making requests to the Infobip API from our Node.js application.
  • Prisma: A modern ORM (Object-Relational Mapper) for Node.js and TypeScript, used for database interactions (schema definition, migrations, type-safe queries). We'll use it with SQLite for simplicity in this guide, but it easily adapts to PostgreSQL, MySQL, etc.
  • dotenv: A module to load environment variables from a .env file into process.env.
  • pino: Fastify's default high-performance JSON logger.
  • uuid: For generating unique identifiers (specifically bulk IDs).
  • Jest/Vitest: A testing framework for writing unit and integration tests. (We'll provide examples).
  • Docker: For containerizing the application for consistent deployment.

System Architecture:

+-------------+       +-----------------+       +-----------------+       +------------------+
|   Client    |------>|  Fastify App    |<----->|  Prisma (ORM)   |<----->| Database (SQLite)|
| (e.g., UI,  |       | (API Endpoints, |       | (Data Access)   |       +------------------+
| Postman)    |       |  Controllers,   |       +-----------------+
+-------------+       |  Services)      |
                      +--------|--------+
                               |
                               v
                      +-----------------+
                      |  Infobip API    |
                      | (SMS Scheduling)|
                      +-----------------+
  1. Client: Initiates requests to schedule, view, reschedule, or cancel SMS messages.
  2. Fastify App: Receives requests, validates input, interacts with the InfobipService and DatabaseService.
  3. InfobipService: Contains logic to interact with the Infobip API endpoints for scheduling and management.
  4. DatabaseService (via Prisma): Stores metadata about scheduled jobs (like the bulkId returned by Infobip) and potentially links it to internal application data.
  5. Infobip API: The external service that actually handles the SMS scheduling and sending.
  6. Database: Persists information about the scheduled jobs managed by our application.

Prerequisites:

  • Node.js (v18 or later recommended) and npm/yarn installed.
  • An active Infobip account (Sign up for free). You'll need your API Key and Base URL.
  • Basic understanding of JavaScript (including ES Modules), Node.js, REST APIs, and asynchronous programming.
  • A code editor (like VS Code).
  • Optional: Docker Desktop installed for containerization.
  • Optional: Postman or curl for testing API endpoints.

Final Outcome:

A deployable Fastify application with API endpoints to fully manage the lifecycle of scheduled SMS messages via Infobip, complete with logging, error handling, database persistence, and basic security considerations.


1. Setting up the Project

Let's initialize our Fastify project and set up the basic structure and dependencies.

Step 1: Initialize Node.js Project

Open your terminal and create a new project directory:

mkdir fastify-infobip-scheduler
cd fastify-infobip-scheduler
npm init -y

Step 2: Configure package.json for ES Modules

Since we'll be using import/export syntax throughout the project, add "type": "module" to your package.json:

{
  "name": "fastify-infobip-scheduler",
  "version": "1.0.0",
  "description": "",
  "main": "src/server.js",
  "type": "module",
  "scripts": {

  },
  "keywords": [],
  "author": "",
  "license": "ISC"

}
  • Why: This tells Node.js to interpret .js files in this project as ES Modules, allowing the use of import and export statements natively.

Step 3: Install Fastify and Core Dependencies

npm install fastify @fastify/env axios prisma @prisma/client dotenv uuid
  • fastify: The core framework.
  • @fastify/env: For loading and validating environment variables.
  • axios: For making HTTP requests to the Infobip API.
  • prisma, @prisma/client: The Prisma CLI and runtime client.
  • dotenv: Loads .env file (though @fastify/env handles this too, dotenv can be useful for scripts like seeding).
  • uuid: To generate unique bulk IDs for Infobip requests.

Step 4: Install Development Dependencies

npm install --save-dev nodemon concurrently pino-pretty @types/node ts-node typescript jest @types/jest
  • nodemon: Automatically restarts the server during development on file changes.
  • concurrently: Runs multiple commands concurrently (useful for watching files and running the server).
  • pino-pretty: For human-readable logs during development (used only by the dev script).
  • typescript, ts-node, @types/node: Although we write JS, Prisma works best with TS tooling installed for generation.
  • jest, @types/jest: Testing framework (as discussed in Section 13).

Step 5: Configure package.json Scripts

Add the following scripts to your package.json:

{

  "scripts": {
    "dev": "nodemon src/server.js | pino-pretty",
    "start": "node src/server.js",
    "prisma:generate": "prisma generate",
    "prisma:migrate": "prisma migrate dev",
    "prisma:studio": "prisma studio",
    "prisma:seed": "node prisma/seed.js",
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
  },

}
  • Note: The test script includes node --experimental-vm-modules which is often required for Jest to work correctly with ES Modules.

Step 6: Set up Project Structure

Create the following directories and files:

fastify-infobip-scheduler/
β”œβ”€β”€ prisma/
β”‚   β”œβ”€β”€ schema.prisma
β”‚   └── seed.js
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   └── smsController.js
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── smsRoutes.js
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ infobipService.js
β”‚   β”‚   └── databaseService.js
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── environment.js
β”‚   β”œβ”€β”€ app.js
β”‚   └── server.js
β”œβ”€β”€ tests/
β”‚   └── smsController.test.js # Example test file
β”œβ”€β”€ .env
β”œβ”€β”€ .env.template
β”œβ”€β”€ .gitignore
└── package.json

Step 7: Create .gitignore

Create a .gitignore file in the root directory. Migration SQL files should be committed.

# .gitignore
node_modules/
.env
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Prisma
# Do NOT ignore migration SQL files: prisma/migrations/*/*.sql
prisma/dev.db*
prisma/dev.db-journal* # Ignore SQLite journal files

# Test results / coverage
coverage/

Step 8: Create .env.template and .env

Create .env.template with the required variables:

.env

# .env.template
# Infobip Credentials (Get from your Infobip account dashboard)
INFOBIP_BASE_URL=your_infobip_base_url_here # e.g., xyz.api.infobip.com
INFOBIP_API_KEY=your_infobip_api_key_here

# Application Settings
PORT=3000
HOST=0.0.0.0
LOG_LEVEL=info
NODE_ENV=development # Set to 'production' in production

# Database (Using SQLite for this guide)
DATABASE_URL="file:./prisma/dev.db"

# Sentry DSN (Optional - for error tracking in Section 10)
# SENTRY_DSN=your_sentry_dsn_here

Now, create a .env file by copying .env.template and fill in your actual Infobip Base URL and API Key. Never commit your .env file to version control.

Step 9: Configure Environment Loading (src/config/environment.js)

This file defines the schema for @fastify/env to validate and load environment variables.

const environmentSchema = {
  type: 'object',
  required: ['INFOBIP_BASE_URL', 'INFOBIP_API_KEY', 'DATABASE_URL', 'PORT', 'HOST'],
  properties: {
    INFOBIP_BASE_URL: { type: 'string', description: 'Base URL for Infobip API' },
    INFOBIP_API_KEY: { type: 'string', description: 'API Key for Infobip' },
    DATABASE_URL: { type: 'string', description: 'Connection URL for the database' },
    PORT: { type: 'number', default: 3000 },
    HOST: { type: 'string', default: '0.0.0.0' },
    LOG_LEVEL: { type: 'string', default: 'info' },
    NODE_ENV: { type: 'string', enum: ['development', 'production', 'test'], default: 'development'},
    SENTRY_DSN: { type: 'string', description: 'Sentry DSN for error tracking (Optional)' }
  },
};

const options = {
  confKey: 'config',
  schema: environmentSchema,
  dotenv: true,

};

export default options;
  • Why: Using @fastify/env provides automatic validation and type coercion for environment variables, preventing runtime errors due to misconfiguration. It centralizes environment management.

Step 10: Configure Prisma (prisma/schema.prisma)

Define the database schema. We'll create a simple table to track our scheduled jobs.

Prisma

// prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite" // Or postgresql, mysql, etc.
  url      = env("DATABASE_URL")
}

// Model to store information about scheduled SMS jobs
model ScheduledSmsJob {
  id          String   @id @default(cuid()) // Unique job ID in our system
  bulkId      String   @unique // The Bulk ID returned by Infobip
  status      String   // e.g., PENDING, CANCELED, (Could be an enum later)
  scheduledAt DateTime // The time the message is scheduled to be sent
  recipient   String   // Store the recipient phone number
  messageText String   // Store the message content (optional, for reference)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  // Add indexes for frequently queried fields
  @@index([status])
  @@index([scheduledAt])
}
  • Why: This schema allows us to map the Infobip bulkId to an internal record, track its intended scheduledAt time, status (which we'll manage based on Infobip responses), and other relevant details like the recipient and message text for easier debugging or application logic. @unique on bulkId ensures we don't have duplicate entries for the same Infobip job. Added indexes on status and scheduledAt for potential performance improvements.

Step 11: Initialize Prisma Database

Run the following command to create the initial database file and migration:

npx prisma migrate dev --name init

This will:

  1. Create the prisma/migrations directory containing the SQL migration file.
  2. Create the dev.db SQLite file (or prompt for database creation if using another provider).
  3. Apply the migration.
  4. Generate the Prisma Client (@prisma/client).

You can inspect the database using Prisma Studio:

npx prisma studio

2. Implementing Core Functionality (Services)

Now, let's create the services that encapsulate the logic for interacting with Infobip and our database.

Step 1: Implement Database Service (src/services/databaseService.js)

This service will handle all interactions with our ScheduledSmsJob table using Prisma Client.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function saveJob(data) {
  try {
    return await prisma.scheduledSmsJob.create({ data });
  } catch (error) {

    console.error('Error saving job to database:', error);

    throw new Error('Failed to save job metadata');
  }
}

async function findJobByBulkId(bulkId) {
  try {
    return await prisma.scheduledSmsJob.findUnique({ where: { bulkId } });
  } catch (error) {
    console.error(`Error finding job by bulkId ${bulkId}:`, error);
    throw new Error('Failed to retrieve job metadata');
  }
}

async function updateJobStatus(bulkId, status, scheduledAt = undefined) {
   try {
    const updateData = { status, updatedAt: new Date() };
    if (scheduledAt) {
      updateData.scheduledAt = scheduledAt;
    }
    return await prisma.scheduledSmsJob.update({
      where: { bulkId },
      data: updateData,
    });
  } catch (error) {


    console.error(`Error updating job status for bulkId ${bulkId}:`, error);
    throw new Error('Failed to update job status');
  }
}

async function disconnectPrisma() {
    await prisma.$disconnect();
}

export default {
  prisma,
  saveJob,
  findJobByBulkId,
  updateJobStatus,
  disconnectPrisma,

};
  • Why: Encapsulating database logic in a service makes the code modular, testable, and easier to manage. It separates database concerns from API/controller logic. Includes basic error handling and exports the Prisma instance and a disconnect function for graceful shutdown.

Step 2: Implement Infobip Service (src/services/infobipService.js)

This service handles all communication with the Infobip API.

import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';

let INFOBIP_BASE_URL;
let INFOBIP_API_KEY;
let infobipApi;

function initializeInfobipService(config) {
  if (!config.INFOBIP_BASE_URL || !config.INFOBIP_API_KEY) {
    throw new Error('Infobip Base URL and API Key must be configured.');
  }
  INFOBIP_BASE_URL = config.INFOBIP_BASE_URL;
  INFOBIP_API_KEY = config.INFOBIP_API_KEY;


  infobipApi = axios.create();


  infobipApi.interceptors.request.use((axiosConfig) => {
    axiosConfig.baseURL = `https://${INFOBIP_BASE_URL}`;
    axiosConfig.headers['Authorization'] = `App ${INFOBIP_API_KEY}`;
    axiosConfig.headers['Content-Type'] = 'application/json';
    axiosConfig.headers['Accept'] = 'application/json';
    return axiosConfig;
  }, (error) => {
    return Promise.reject(error);
  });
}

async function scheduleSms(recipient, messageText, sendAt, sender = 'InfoSMS') {
  if (!infobipApi) throw new Error('Infobip service not initialized.');

  const bulkId = `bulk-${uuidv4()}`;

  const payload = {
    messages: [
      {
        destinations: [{ to: recipient }],
        from: sender,
        text: messageText,
      },
    ],
    bulkId: bulkId,
    sendAt: sendAt,
  };

  const endpoint = '/sms/2/bulks';
  console.info(`Scheduling SMS via Infobip: POST ${endpoint} for recipient ${recipient}`);

  try {
    const response = await infobipApi.post(endpoint, payload);




    const returnedBulkId = response.data?.bulkId;
    const initialStatus = response.data?.status || 'PENDING';

    if (!returnedBulkId || returnedBulkId !== bulkId) {
         console.warn(`Infobip schedule response bulkId mismatch or missing. Sent: ${bulkId}, Received: ${returnedBulkId}`);

    }

    return {
        bulkId: bulkId,
        status: initialStatus,
        sendAt: sendAt,
        apiResponse: response.data
    };
  } catch (error) {
    const errorData = error.response?.data;
    const errorMessage = errorData?.requestError?.serviceException?.text || error.message;
    console.error(`Infobip API Error (scheduleSms - POST ${endpoint}): Status ${error.response?.status}, Message: ${errorMessage}`, errorData);
    throw new Error(`Failed to schedule SMS via Infobip: ${errorMessage}`);
  }
}

async function getScheduledSms(bulkId) {
  if (!infobipApi) throw new Error('Infobip service not initialized.');
  if (!bulkId) throw new Error('Bulk ID is required.');

  const endpoint = '/sms/2/bulks';
  console.info(`Getting scheduled SMS via Infobip: GET ${endpoint}?bulkId=${bulkId}`);

  try {
    const response = await infobipApi.get(endpoint, { params: { bulkId } });




    const bulks = response.data?.bulks;
    if (bulks && bulks.length > 0) {
         return bulks[0];
    } else if (response.data?.bulkId === bulkId) {

         return response.data;
    } else {
        throw new Error(`Scheduled bulk ${bulkId} not found in Infobip response.`);
    }
  } catch (error) {
    const errorData = error.response?.data;
    const errorMessage = errorData?.requestError?.serviceException?.text || error.message;
    console.error(`Infobip API Error (getScheduledSms - GET ${endpoint}): Status ${error.response?.status}, Message: ${errorMessage}`, errorData);
     if (error.response?.status === 404 || errorMessage.toLowerCase().includes('not found')) {
         throw new Error(`Scheduled bulk ${bulkId} not found.`);
     }
    throw new Error(`Failed to retrieve scheduled SMS ${bulkId}: ${errorMessage}`);
  }
}

async function rescheduleSms(bulkId, newSendAt) {
  if (!infobipApi) throw new Error('Infobip service not initialized.');
  if (!bulkId || !newSendAt) throw new Error('Bulk ID and new SendAt time are required.');

  const endpoint = '/sms/2/bulks';
  const payload = { sendAt: newSendAt };
  console.info(`Rescheduling SMS via Infobip: PUT ${endpoint}?bulkId=${bulkId}`);

  try {

    const response = await infobipApi.put(endpoint, payload, { params: { bulkId } });




    return response.data;
  } catch (error) {
    const errorData = error.response?.data;
    const errorMessage = errorData?.requestError?.serviceException?.text || error.message;
    console.error(`Infobip API Error (rescheduleSms - PUT ${endpoint}): Status ${error.response?.status}, Message: ${errorMessage}`, errorData);
     if (error.response?.status === 404 || errorMessage.toLowerCase().includes('not found')) {
         throw new Error(`Scheduled bulk ${bulkId} not found for rescheduling.`);
     }

    throw new Error(`Failed to reschedule SMS ${bulkId}: ${errorMessage}`);
  }
}

async function getScheduledSmsStatus(bulkId) {
  if (!infobipApi) throw new Error('Infobip service not initialized.');
  if (!bulkId) throw new Error('Bulk ID is required.');

  const endpoint = '/sms/2/bulks/status';
  console.info(`Getting status via Infobip: GET ${endpoint}?bulkId=${bulkId}`);

  try {
    const response = await infobipApi.get(endpoint, { params: { bulkId } });




    const bulks = response.data?.bulks;
    if (bulks && bulks.length > 0) {
         return bulks[0];
    } else if (response.data?.bulkId === bulkId && response.data?.status) {

         return response.data;
    } else {
        throw new Error(`Scheduled bulk status for ${bulkId} not found in Infobip response.`);
    }
  } catch (error) {
    const errorData = error.response?.data;
    const errorMessage = errorData?.requestError?.serviceException?.text || error.message;
    console.error(`Infobip API Error (getScheduledSmsStatus - GET ${endpoint}): Status ${error.response?.status}, Message: ${errorMessage}`, errorData);
     if (error.response?.status === 404 || errorMessage.toLowerCase().includes('not found')) {
         throw new Error(`Scheduled bulk status for ${bulkId} not found.`);
     }
    throw new Error(`Failed to get scheduled SMS status for ${bulkId}: ${errorMessage}`);
  }
}

async function updateScheduledSmsStatus(bulkId, status) {
  if (!infobipApi) throw new Error('Infobip service not initialized.');
  if (!bulkId || !status) throw new Error('Bulk ID and status are required.');


  if (status.toUpperCase() !== 'CANCELED') {
        throw new Error('Only cancellation (""CANCELED"") is supported via this status update function.');
    }

  const endpoint = '/sms/2/bulks/status';
  const payload = { status: status.toUpperCase() };
  console.info(`Updating status via Infobip: PUT ${endpoint}?bulkId=${bulkId}`);

  try {

    const response = await infobipApi.put(endpoint, payload, { params: { bulkId } });




    return response.data;
  } catch (error) {
    const errorData = error.response?.data;
    const errorMessage = errorData?.requestError?.serviceException?.text || error.message;
    console.error(`Infobip API Error (updateScheduledSmsStatus - PUT ${endpoint}): Status ${error.response?.status}, Message: ${errorMessage}`, errorData);
    if (error.response?.status === 404 || errorMessage.toLowerCase().includes('not found')) {
         throw new Error(`Scheduled bulk ${bulkId} not found for status update.`);
     }

    throw new Error(`Failed to update scheduled SMS status for ${bulkId}: ${errorMessage}`);
  }
}

export default {
  initializeInfobipService,
  scheduleSms,
  getScheduledSms,
  rescheduleSms,
  getScheduledSmsStatus,
  updateScheduledSmsStatus,
};
  • Why: This service abstracts Infobip API interactions.
  • Uses a centralized axios instance with interceptors.
  • Maps functions to business actions and potential Infobip endpoints.
  • Generates unique bulkId client-side using uuid.
  • Includes stronger comments emphasizing the need to verify Infobip endpoints and response structures against official documentation.
  • Basic error handling logs Infobip errors and throws application errors.
  • Uses an initialize function for simplicity, with notes on DI being a better pattern for larger apps.

3. Building the API Layer (Routes and Controllers)

Let's expose the service functionality through Fastify routes and controllers.

Step 1: Create SMS Controller (src/controllers/smsController.js)

Handles requests, validates input, calls services, and formats responses.

import infobipService from '../services/infobipService.js';
import databaseService from '../services/databaseService.js';

const phoneRegex = '^\\+[1-9]\\d{1,14}$';

const scheduleSmsSchema = {
  body: {
    type: 'object',
    required: ['recipient', 'messageText', 'sendAt'],
    properties: {
      recipient: {
          type: 'string',
          description: 'E.164 format required (e.g., +12223334444)',
          pattern: phoneRegex,
          errorMessage: 'Recipient must be a valid phone number in E.164 format (e.g., +12223334444)'
      },
      messageText: { type: 'string', minLength: 1, maxLength: 1600 },
      sendAt: {
          type: 'string',
          format: 'date-time',
          description: 'ISO 8601 format required (e.g., 2025-09-01T12:00:00.000Z)',
          errorMessage: 'sendAt must be a valid ISO 8601 date-time string'
       },
      sender: { type: 'string', description: 'Optional sender ID' },
    },
    additionalProperties: false,
  },
  response: {
    201: {
      description: 'SMS scheduled successfully',
      type: 'object',
      properties: {
        message: { type: 'string' },
        jobId: { type: 'string', description: 'Internal application job ID' },
        bulkId: { type: 'string', description: 'Infobip bulk ID' },
        status: { type: 'string', description: 'Initial status (e.g., PENDING)' },
        scheduledAt: { type: 'string', format: 'date-time' },
      },
    },

  },
};

const bulkIdParamsSchema = {
    params: {
        type: 'object',
        required: ['bulkId'],
        properties: {
            bulkId: { type: 'string', description: 'The Infobip Bulk ID (usually starts with bulk-)' }
        },
        additionalProperties: false,
    }
};

const rescheduleSmsSchema = {
    ...bulkIdParamsSchema,
    body: {
        type: 'object',
        required: ['sendAt'],
        properties: {
             sendAt: {
                 type: 'string',
                 format: 'date-time',
                 description: 'New ISO 8601 scheduled time',
                 errorMessage: 'sendAt must be a valid ISO 8601 date-time string'
            },
        },
        additionalProperties: false,
    },
     response: {
        200: {
            description: 'SMS rescheduled successfully',
            type: 'object',
            properties: {
                message: { type: 'string' },
                bulkId: { type: 'string' },
                newScheduledAt: { type: 'string', format: 'date-time', description: 'Confirmed new schedule time from Infobip' },
            },
        },
    },
};

const updateStatusSchema = {
     ...bulkIdParamsSchema,
     body: {
        type: 'object',
        required: ['status'],
        properties: {
             status: {
                type: 'string',
                enum: ['CANCELED'],
                description: 'Must be "CANCELED" to cancel the scheduled SMS',
                errorMessage: 'Status must be "CANCELED"'
            }
        },
        additionalProperties: false,
    },
     response: {
        200: {
            description: 'SMS status updated successfully',
            type: 'object',
            properties: {
                message: { type: 'string' },
                bulkId: { type: 'string' },
                status: { type: 'string', description: 'Confirmed status from Infobip (e.g., CANCELED)' },
            },
        },
    },
};

async function scheduleSmsHandler(request, reply) {
  const { recipient, messageText, sendAt, sender } = request.body;


   const scheduleDate = new Date(sendAt);
   if (scheduleDate <= new Date()) {
       return reply.code(400).send({ error: 'Bad Request', message: 'sendAt must be in the future.' });
   }


  try {
    request.log.info(`Received schedule request for ${recipient} at ${sendAt}`);

    const infobipResponse = await infobipService.scheduleSms(recipient, messageText, sendAt, sender);
    request.log.info(`Infobip scheduling initiated for bulkId: ${infobipResponse.bulkId}, initial status: ${infobipResponse.status}`);


    const jobData = {
      bulkId: infobipResponse.bulkId,
      status: infobipResponse.status,
      scheduledAt: new Date(sendAt),
      recipient: recipient,
      messageText: messageText,
    };
    const savedJob = await databaseService.saveJob(jobData);
    request.log.info(`Saved scheduled job metadata with internal ID: ${savedJob.id}`);


    return reply.code(201).send({
      message: 'SMS scheduled successfully.',
      jobId: savedJob.id,
      bulkId: savedJob.bulkId,
      status: savedJob.status,
      scheduledAt: savedJob.scheduledAt.toISOString(),
    });

  } catch (error) {
    request.log.error({ err: error }, `Error scheduling SMS for ${recipient}: ${error.message}`);



    throw error;
  }
}

export {
    scheduleSmsSchema,
    bulkIdParamsSchema,
    rescheduleSmsSchema,
    updateStatusSchema,
    scheduleSmsHandler,

};

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