DEV Community

Hamza Khan
Hamza Khan

Posted on

πŸ“… Building an Automated Scheduling System with Next.js πŸš€

An automated scheduling system can streamline appointment booking, manage time slots, and send remindersβ€”all without manual effort. In this post, we’ll create a scheduling system in Next.js that includes real-time availability, reminder emails, and an easy-to-use calendar. Perfect for booking appointments, consultations, or even team meetings!

πŸ› οΈ Project Setup

To build our scheduling system, we'll use:

  1. Next.js for the frontend and server-side APIs.
  2. MySQL to store appointments and time slots.
  3. Nodemailer for email reminders.
  4. React-Calendar for date selection.

πŸš€ Getting Started

Initialize your Next.js project:

npx create-next-app scheduling-system
cd scheduling-system
npm install mysql react-calendar nodemailer
Enter fullscreen mode Exit fullscreen mode

πŸ“… Setting Up the Database

First, set up your MySQL database. We’ll create tables for appointments and time slots.

1. Create Database Tables

CREATE TABLE time_slots (
  id INT PRIMARY KEY AUTO_INCREMENT,
  slot_time TIME NOT NULL,
  is_available BOOLEAN DEFAULT true
);

CREATE TABLE appointments (
  id INT PRIMARY KEY AUTO_INCREMENT,
  slot_id INT,
  customer_name VARCHAR(255),
  customer_email VARCHAR(255),
  appointment_date DATE,
  FOREIGN KEY (slot_id) REFERENCES time_slots(id)
);
Enter fullscreen mode Exit fullscreen mode

πŸ§‘β€πŸ’» Building the Next.js API

Now, let’s create API routes in pages/api for managing appointments and availability.

1. Get Available Slots

In pages/api/slots.js:

import db from '../../db';

export default function handler(req, res) {
  db.query('SELECT * FROM time_slots WHERE is_available = true', (err, results) => {
    if (err) throw err;
    res.status(200).json(results);
  });
}
Enter fullscreen mode Exit fullscreen mode

2. Book an Appointment

In pages/api/book.js:

import db from '../../db';

export default function handler(req, res) {
  const { customerName, customerEmail, slotId, appointmentDate } = req.body;

  // Mark the slot as booked
  db.query('UPDATE time_slots SET is_available = false WHERE id = ?', [slotId], (err) => {
    if (err) throw err;

    // Create an appointment record
    db.query(
      'INSERT INTO appointments (slot_id, customer_name, customer_email, appointment_date) VALUES (?, ?, ?, ?)',
      [slotId, customerName, customerEmail, appointmentDate],
      (err) => {
        if (err) throw err;
        res.status(201).json({ message: 'Appointment booked!' });
      }
    );
  });
}
Enter fullscreen mode Exit fullscreen mode

πŸ“† Creating the Scheduling UI

Using react-calendar, let’s create a calendar interface where users can view available slots and book appointments.

1. Install react-calendar

npm install react-calendar
Enter fullscreen mode Exit fullscreen mode

2. Schedule Component with Calendar

Create a component in components/Schedule.js:

import { useState, useEffect } from 'react';
import Calendar from 'react-calendar';
import axios from 'axios';

export default function Schedule() {
  const [date, setDate] = useState(new Date());
  const [slots, setSlots] = useState([]);

  useEffect(() => {
    async function fetchSlots() {
      const { data } = await axios.get('/api/slots');
      setSlots(data);
    }
    fetchSlots();
  }, []);

  const handleBooking = async (slotId) => {
    await axios.post('/api/book', {
      customerName: 'Jane Doe',
      customerEmail: 'jane.doe@example.com',
      slotId,
      appointmentDate: date
    });
    alert('Appointment Booked!');
  };

  return (
    <div>
      <Calendar onChange={setDate} value={date} />
      <h3>Available Slots on {date.toDateString()}:</h3>
      <ul>
        {slots.map(slot => (
          <li key={slot.id}>
            {slot.slot_time}
            <button onClick={() => handleBooking(slot.id)}>Book</button>
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

πŸ“§ Setting Up Automated Email Reminders

Install Nodemailer for sending email reminders:

npm install nodemailer
Enter fullscreen mode Exit fullscreen mode

In utils/sendReminderEmail.js, define an email reminder function:

import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your_email@gmail.com',
    pass: 'your_password',
  },
});

export const sendReminderEmail = async (email, appointmentDate) => {
  const mailOptions = {
    from: 'your_email@gmail.com',
    to: email,
    subject: 'Appointment Reminder',
    text: `Reminder: You have an appointment on ${appointmentDate}.`
  };

  await transporter.sendMail(mailOptions);
};
Enter fullscreen mode Exit fullscreen mode

⏰ Setting Up a Reminder Scheduler

To automate reminders, we can use cron jobs with node-cron.

npm install node-cron
Enter fullscreen mode Exit fullscreen mode

In scripts/reminderScheduler.js, set up a cron job:

import cron from 'node-cron';
import db from '../db';
import { sendReminderEmail } from '../utils/sendReminderEmail';

cron.schedule('0 9 * * *', () => { // Run every day at 9 AM
  const today = new Date();
  db.query('SELECT * FROM appointments WHERE appointment_date = ?', [today], (err, results) => {
    if (err) throw err;
    results.forEach(async (appointment) => {
      const { customer_email, appointment_date } = appointment;
      await sendReminderEmail(customer_email, appointment_date);
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

Add the scheduler to your application startup script to run in the background.

πŸŽ‰ Wrapping Up

Our automated scheduling system is now complete! With Next.js, MySQL, a calendar, and automated email reminders, this setup will make scheduling seamless.

Top comments (0)