Skip to contentSkip to navigationSkip to topbar
On this page

Send Appointment Reminders with Node.js and Express


(information)

Info

Ahoy! We now recommend you build your appointment reminders with Twilio's built-in Message Scheduling functionality. Head on over to the Message Scheduling documentation to learn more about scheduling messages.

This Node.js Express(link takes you to an external page) web application sends out reminders for future appointments that customers can create through the application as well. This is done through a background job that runs every minute.

On this tutorial we'll point out the key bits of code that make this application work. Check out the project README on GitHub(link takes you to an external page) to see how to run the code yourself.

Check out how Yelp uses SMS to confirm restaurant reservations for diners.(link takes you to an external page)

Let's get started! Click the button below to get started.


Configure the application to use Twilio

configure-the-application-to-use-twilio page anchor

Before we can use the Twilio API to send reminder text messages we need to configure our account credentials. These can be found on your Twilio Console. You'll also need an SMS-enabled phone number - you can find or purchase a new one here.

Configure the application to use Twilio

configure-the-application-to-use-twilio-1 page anchor
1
TWILIO_ACCOUNT_SID=Your-Account-SID
2
TWILIO_AUTH_TOKEN=Your-Twilio-Auth-Token
3
TWILIO_PHONE_NUMBER=Your-Twilio-Phone-Number
4
MONGO_URL=Mongo-Url
5
MONGO_URL_TEST=mongodb://127.0.0.1:27017/appointment-reminders
6
NODE_ENV=production

In order to send an appointment reminder we need to have an appointment first!


Create a new appointment

create-a-new-appointment page anchor

On the controller we input the information required (a customer's name and phone number, plus a time and date for the appointment) by saving it on an Appointment model.

We use mongoose(link takes you to an external page) in this application to store our model in MongoDB(link takes you to an external page).

1
var AppointmentSchema = new mongoose.Schema({
2
name:String,
3
phoneNumber: String,
4
notification : Number,
5
timeZone : String,
6
time : {type : Date, index : true}
7
});

routes/appointments.js

1
'use strict';
2
3
const express = require('express');
4
const momentTimeZone = require('moment-timezone');
5
const moment = require('moment');
6
const Appointment = require('../models/appointment');
7
const router = new express.Router();
8
9
10
const getTimeZones = function() {
11
return momentTimeZone.tz.names();
12
};
13
14
// GET: /appointments
15
router.get('/', function(req, res, next) {
16
Appointment.find()
17
.then(function(appointments) {
18
res.render('appointments/index', {appointments: appointments});
19
});
20
});
21
22
// GET: /appointments/create
23
router.get('/create', function(req, res, next) {
24
res.render('appointments/create', {
25
timeZones: getTimeZones(),
26
appointment: new Appointment({name: '',
27
phoneNumber: '',
28
notification: '',
29
timeZone: '',
30
time: ''})});
31
});
32
33
// POST: /appointments
34
router.post('/', function(req, res, next) {
35
const name = req.body.name;
36
const phoneNumber = req.body.phoneNumber;
37
const notification = req.body.notification;
38
const timeZone = req.body.timeZone;
39
const time = moment(req.body.time, 'MM-DD-YYYY hh:mma');
40
41
const appointment = new Appointment({name: name,
42
phoneNumber: phoneNumber,
43
notification: notification,
44
timeZone: timeZone,
45
time: time});
46
appointment.save()
47
.then(function() {
48
res.redirect('/');
49
});
50
});
51
52
// GET: /appointments/:id/edit
53
router.get('/:id/edit', function(req, res, next) {
54
const id = req.params.id;
55
Appointment.findOne({_id: id})
56
.then(function(appointment) {
57
res.render('appointments/edit', {timeZones: getTimeZones(),
58
appointment: appointment});
59
});
60
});
61
62
// POST: /appointments/:id/edit
63
router.post('/:id/edit', function(req, res, next) {
64
const id = req.params.id;
65
const name = req.body.name;
66
const phoneNumber = req.body.phoneNumber;
67
const notification = req.body.notification;
68
const timeZone = req.body.timeZone;
69
const time = moment(req.body.time, 'MM-DD-YYYY hh:mma');
70
71
Appointment.findOne({_id: id})
72
.then(function(appointment) {
73
appointment.name = name;
74
appointment.phoneNumber = phoneNumber;
75
appointment.notification = notification;
76
appointment.timeZone = timeZone;
77
appointment.time = time;
78
79
appointment.save()
80
.then(function() {
81
res.redirect('/');
82
});
83
});
84
});
85
86
// POST: /appointments/:id/delete
87
router.post('/:id/delete', function(req, res, next) {
88
const id = req.params.id;
89
90
Appointment.remove({_id: id})
91
.then(function() {
92
res.redirect('/');
93
});
94
});
95
96
module.exports = router;

Now that we have our Appointment created, let's see how to schedule a reminder for it.


Schedule a job to send reminders

schedule-a-job-to-send-reminders page anchor

Every minute we'd like our application to check the appointments database to see if any appointments are coming up that require reminders to be sent out.

To do this we use node-cron(link takes you to an external page).

We configure on the start function both the job code we'd like to run, and the interval on which to run it. Then we call it from the application execution entry point like this: scheduler.start()

Schedule a job to send reminders

schedule-a-job-to-send-reminders-1 page anchor

scheduler.js

1
'use strict';
2
3
const CronJob = require('cron').CronJob;
4
const notificationsWorker = require('./workers/notificationsWorker');
5
const moment = require('moment');
6
7
const schedulerFactory = function() {
8
return {
9
start: function() {
10
new CronJob('00 * * * * *', function() {
11
console.log('Running Send Notifications Worker for ' +
12
moment().format());
13
notificationsWorker.run();
14
}, null, true, '');
15
},
16
};
17
};
18
19
module.exports = schedulerFactory();

This start function uses a notificationsWorker, next we'll see how it works.


Create a worker function to run the job

create-a-worker-function-to-run-the-job page anchor

To actually execute our recurring job logic, we create a worker function which uses a Static Model Method(link takes you to an external page) to query the database for upcoming appointments and sends reminders as necessary.

Create a worker function to run the job

create-a-worker-function-to-run-the-job-1 page anchor

workers/notificationsWorker.js

1
'use strict';
2
3
const Appointment = require('../models/appointment');
4
5
const notificationWorkerFactory = function() {
6
return {
7
run: function() {
8
Appointment.sendNotifications();
9
},
10
};
11
};
12
13
module.exports = notificationWorkerFactory();

Next, let's see how the Appointment job works in detail.


Find appointments that need reminders

find-appointments-that-need-reminders page anchor

Our recurring job uses a static model method of the Appointment model to query the database for appointments coming up in the current minute and send out reminder messages using a Twilio REST Client we previously initialized with our Twilio account credentials.

Because of the fact that appointments are defined in different time zones, we use Moment.js library(link takes you to an external page) in order to properly query every upcoming appointment considering its time zone.

Find appointments that need reminders

find-appointments-that-need-reminders-1 page anchor

models/appointment.js

1
'use strict';
2
3
const mongoose = require('mongoose');
4
const moment = require('moment');
5
const cfg = require('../config');
6
const Twilio = require('twilio');
7
8
const AppointmentSchema = new mongoose.Schema({
9
name: String,
10
phoneNumber: String,
11
notification: Number,
12
timeZone: String,
13
time: {type: Date, index: true},
14
});
15
16
AppointmentSchema.methods.requiresNotification = function(date) {
17
return Math.round(moment.duration(moment(this.time).tz(this.timeZone).utc()
18
.diff(moment(date).utc())
19
).asMinutes()) === this.notification;
20
};
21
22
AppointmentSchema.statics.sendNotifications = function(callback) {
23
// now
24
const searchDate = new Date();
25
Appointment
26
.find()
27
.then(function(appointments) {
28
appointments = appointments.filter(function(appointment) {
29
return appointment.requiresNotification(searchDate);
30
});
31
if (appointments.length > 0) {
32
sendNotifications(appointments);
33
}
34
});
35
36
/**
37
* Send messages to all appoinment owners via Twilio
38
* @param {array} appointments List of appointments.
39
*/
40
function sendNotifications(appointments) {
41
const client = new Twilio(cfg.twilioAccountSid, cfg.twilioAuthToken);
42
appointments.forEach(function(appointment) {
43
// Create options to send the message
44
const options = {
45
to: `+ ${appointment.phoneNumber}`,
46
from: cfg.twilioPhoneNumber,
47
/* eslint-disable max-len */
48
body: `Hi ${appointment.name}. Just a reminder that you have an appointment coming up.`,
49
/* eslint-enable max-len */
50
};
51
52
// Send the message!
53
client.messages.create(options, function(err, response) {
54
if (err) {
55
// Just log it for now
56
console.error(err);
57
} else {
58
// Log the last few digits of a phone number
59
let masked = appointment.phoneNumber.substr(0,
60
appointment.phoneNumber.length - 5);
61
masked += '*****';
62
console.log(`Message sent to ${masked}`);
63
}
64
});
65
});
66
67
// Don't wait on success/failure, just indicate all messages have been
68
// queued for delivery
69
if (callback) {
70
callback.call();
71
}
72
}
73
};
74
75
76
const Appointment = mongoose.model('appointment', AppointmentSchema);
77
module.exports = Appointment;

All that is left is to send the actual SMS. We'll see that next.


Send reminder messages with the Twilio API

send-reminder-messages-with-the-twilio-api page anchor

This code is called for every appointment coming up that requires a reminder to be sent. We provide a configuration object with a to field, which is the customer's phone number, a from field, which is a number in our account, and a body field, which contains the text of the message. Then we pass it to the sendMessage method along with a callback to log errors and success.

Send reminder messages with the Twilio API

send-reminder-messages-with-the-twilio-api-1 page anchor

models/appointment.js

1
'use strict';
2
3
const mongoose = require('mongoose');
4
const moment = require('moment');
5
const cfg = require('../config');
6
const Twilio = require('twilio');
7
8
const AppointmentSchema = new mongoose.Schema({
9
name: String,
10
phoneNumber: String,
11
notification: Number,
12
timeZone: String,
13
time: {type: Date, index: true},
14
});
15
16
AppointmentSchema.methods.requiresNotification = function(date) {
17
return Math.round(moment.duration(moment(this.time).tz(this.timeZone).utc()
18
.diff(moment(date).utc())
19
).asMinutes()) === this.notification;
20
};
21
22
AppointmentSchema.statics.sendNotifications = function(callback) {
23
// now
24
const searchDate = new Date();
25
Appointment
26
.find()
27
.then(function(appointments) {
28
appointments = appointments.filter(function(appointment) {
29
return appointment.requiresNotification(searchDate);
30
});
31
if (appointments.length > 0) {
32
sendNotifications(appointments);
33
}
34
});
35
36
/**
37
* Send messages to all appoinment owners via Twilio
38
* @param {array} appointments List of appointments.
39
*/
40
function sendNotifications(appointments) {
41
const client = new Twilio(cfg.twilioAccountSid, cfg.twilioAuthToken);
42
appointments.forEach(function(appointment) {
43
// Create options to send the message
44
const options = {
45
to: `+ ${appointment.phoneNumber}`,
46
from: cfg.twilioPhoneNumber,
47
/* eslint-disable max-len */
48
body: `Hi ${appointment.name}. Just a reminder that you have an appointment coming up.`,
49
/* eslint-enable max-len */
50
};
51
52
// Send the message!
53
client.messages.create(options, function(err, response) {
54
if (err) {
55
// Just log it for now
56
console.error(err);
57
} else {
58
// Log the last few digits of a phone number
59
let masked = appointment.phoneNumber.substr(0,
60
appointment.phoneNumber.length - 5);
61
masked += '*****';
62
console.log(`Message sent to ${masked}`);
63
}
64
});
65
});
66
67
// Don't wait on success/failure, just indicate all messages have been
68
// queued for delivery
69
if (callback) {
70
callback.call();
71
}
72
}
73
};
74
75
76
const Appointment = mongoose.model('appointment', AppointmentSchema);
77
module.exports = Appointment;

That's it! Our application is all set to send out reminders for upcoming appointments.


We hope you found this sample application useful. If you're a Node.js/Express developer working with Twilio you might enjoy these other tutorials:

Workflow Automation

Build a ready-for-scale automated SMS workflow for a vacation rental company.

Browser Calls

Make browser-to-phone and browser-to-browser calls with ease.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.