Skip to contentSkip to navigationSkip to topbar
On this page

Workflow Automation with Node.js and Express


One of the more abstract concepts you'll handle when building your business is what the workflow will look like.

At its core, setting up a standardized workflow is about enabling your service providers (agents, hosts, customer service reps, administrators, and the rest of the gang) to better serve your customers.

To illustrate a very real-world example, today we'll build a Node.js and Express webapp for finding and booking vacation properties — tentatively called Airtng.

Here's how it'll work:

  1. A host creates a vacation property listing
  2. A guest requests a reservation for a property
  3. The host receives an SMS notifying them of the reservation request. The host can either Accept or Reject the reservation
  4. The guest is notified whether a request was rejected or accepted

Learn how Airbnb used Twilio SMS to streamline the rental experience for 60M+ travelers around the world.(link takes you to an external page)


Workflow Building Blocks

workflow-building-blocks page anchor

We'll be using the Twilio REST API to send our users messages at important junctures. Here's a bit more on our API:

  • Sending Messages with Twilio API

Ready to go? Boldly click the button right after this sentence.


For this workflow to work, we need to handle user authentication. We're going to rely on Passport(link takes you to an external page) for Node.js.

Each User will need to have a countryCode and a phoneNumber which will be required to send SMS notifications later.

User Model to handle authentication

user-model-to-handle-authentication page anchor

models/user.js

1
var mongoose = require('mongoose');
2
var passportLocalMongoose = require('passport-local-mongoose');
3
4
var userSchema = new mongoose.Schema({
5
email: { type: String, required: true },
6
username: { type: String, required: true },
7
password: { type: String },
8
countryCode: { type: String, required: true },
9
phoneNumber: { type: String, required: true },
10
date: { type: Date, default: Date.now },
11
});
12
13
userSchema.plugin(passportLocalMongoose);
14
15
var user = mongoose.model('user', userSchema);
16
17
module.exports = user;

Next let's model the vacation properties.


In order to build our rentals company we'll need a way to create the property listings.

The Property belongs to the User who created it (we'll call this user the host moving forward) and contains only two properties: a description and an imageUrl.

The Vacation Property Model

the-vacation-property-model page anchor

models/property.js

1
var mongoose = require('mongoose');
2
3
var propertySchema = new mongoose.Schema({
4
description: { type: String, required: true },
5
imageUrl: { type: String, required: true },
6
date: { type: Date, default: Date.now },
7
owner: {
8
type: mongoose.Schema.Types.ObjectId,
9
ref: 'user'
10
}
11
});
12
13
var property = mongoose.model('property', propertySchema);
14
15
module.exports = property;

Next up, the reservation model.


The Reservation model is at the center of the workflow for this application.

It is responsible for keeping track of:

  • The guest who performed the reservation
  • The vacation_property the guest is requesting (and associated host)
  • The status of the reservation: pending, confirmed, or rejected

models/reservation.js

1
var mongoose = require('mongoose');
2
var deepPopulate = require('mongoose-deep-populate')(mongoose);
3
4
var reservationSchema = new mongoose.Schema({
5
message: { type: String, required: true },
6
status: { type: String, default: 'pending' },
7
date: { type: Date, default: Date.now },
8
property: {
9
type: mongoose.Schema.Types.ObjectId,
10
ref: 'property'
11
},
12
guest: {
13
type: mongoose.Schema.Types.ObjectId,
14
ref: 'user'
15
}
16
});
17
18
reservationSchema.plugin(deepPopulate, {});
19
20
var reservation = mongoose.model('reservation', reservationSchema);
21
22
module.exports = reservation;

Next, let's look at triggering the creation of a new reservation.


The reservation creation form holds only a single field field: the message that will be sent to the host when reserving one of her properties. The rest of the information necessary to create a reservation is taken from the vacation property.

A reservation is created with a default status pending, so when the host replies with an accept or reject response our application knows which reservation to update.

routes/reservations.js

1
var MessagingResponse = require('twilio').twiml.MessagingResponse;
2
var twilio = require('twilio');
3
var express = require('express');
4
var router = express.Router();
5
var Property = require('../models/property');
6
var Reservation = require('../models/reservation');
7
var User = require('../models/user');
8
var notifier = require('../lib/notifier');
9
10
// POST: /reservations
11
router.post('/', function (req, res) {
12
var propertyId = req.body.propertyId;
13
var user = req.user;
14
15
Property.findOne({ _id: propertyId })
16
.then(function (property) {
17
var reservation = new Reservation({
18
message: req.body.message,
19
property: propertyId,
20
guest: user.id
21
});
22
23
return reservation.save();
24
})
25
.then(function () {
26
notifier.sendNotification();
27
res.redirect('/properties');
28
})
29
.catch(function(err) {
30
console.log(err);
31
});
32
});
33
34
// POST: /reservations/handle
35
router.post('/handle', twilio.webhook({validate: false}), function (req, res) {
36
var from = req.body.From;
37
var smsRequest = req.body.Body;
38
39
var smsResponse;
40
41
User.findOne({phoneNumber: from})
42
.then(function (host) {
43
return Reservation.findOne({status: 'pending'});
44
})
45
.then(function (reservation) {
46
if (reservation === null) {
47
throw 'No pending reservations';
48
}
49
reservation.status = smsRequest.toLowerCase() === "accept" ? "confirmed" : "rejected";
50
return reservation.save();
51
})
52
.then(function (reservation) {
53
var message = "You have successfully " + reservation.status + " the reservation";
54
respond(res, message);
55
})
56
.catch(function (err) {
57
var message = "Sorry, it looks like you do not have any reservations to respond to";
58
respond(res, message);
59
});
60
});
61
62
var respond = function(res, message) {
63
var messagingResponse = new MessagingResponse();
64
messagingResponse.message({}, message);
65
66
res.type('text/xml');
67
res.send(messagingResponse.toString());
68
}
69
70
module.exports = router;

In the next step, we'll take a look at how the SMS notification is sent to the host when the reservation is created.


When a reservation is created, we want to notify the owner of said property that someone has made a reservation.

This is where we use Twilio Node Helper Library to send an SMS message to the host, using our Twilio phone number. As you can see, sending SMS messages using Twilio is just a few lines of code.

Now we just have to wait for the host to send an SMS response accepting or rejecting the reservation so we can notify the guest and host that the reservation information is updated.

Send out reservation notifications

send-out-reservation-notifications page anchor

Notify through SMS the host of the new reservation

1
var config = require('../config');
2
var client = require('twilio')(config.accountSid, config.authToken);
3
var Reservation = require('../models/reservation');
4
5
var sendNotification = function() {
6
Reservation.find({status: 'pending'})
7
.deepPopulate('property property.owner guest')
8
.then(function (reservations) {
9
if (reservations.length > 1) {
10
return;
11
}
12
13
var reservation = reservations[0];
14
var owner = reservation.property.owner;
15
16
// Send the notification
17
client.messages.create({
18
to: phoneNumber(owner),
19
from: config.phoneNumber,
20
body: buildMessage(reservation)
21
})
22
.then(function(res) {
23
console.log(res.body);
24
})
25
.catch(function(err) {
26
console.log(err);
27
});
28
});
29
};
30
31
var phoneNumber = function(owner) {
32
return "+" + owner.countryCode + owner.phoneNumber;
33
};
34
35
var buildMessage = function(reservation) {
36
var message = "You have a new reservation request from " + reservation.guest.username +
37
" for " + reservation.property.description + ":\n" +
38
reservation.message + "\n" +
39
"Reply accept or reject";
40
41
return message;
42
};
43
44
exports.sendNotification = sendNotification;

The next step shows how to handle and configure the host's SMS response.


Handle Incoming Messages

handle-incoming-messages page anchor

The reservations/handle endpoint handles our incoming Twilio request and does three things:

  1. Checks for a pending reservation from the incoming user.
  2. Updates the status of the reservation.
  3. Responds to the host and sends notification to the guest.

In the Twilio console(link takes you to an external page), you should change the 'A Message Comes In' webhook to call your application's endpoint in the route /handle:

SMS Webhook.

One way to expose your machine to the world during development is to use ngrok(link takes you to an external page). Your URL for the SMS web hook on your phone number should look something like this:

http://<subdomain>.ngrok.io/handle

An incoming request from Twilio comes with some helpful including the From phone number and the message Body.

We'll use the From parameter to lookup the host and check if she has any pending reservations. If she does, we'll use the message body to check if she accepted or rejected the reservation.

Deal with host responses

deal-with-host-responses page anchor

routes/reservations.js

1
var MessagingResponse = require('twilio').twiml.MessagingResponse;
2
var twilio = require('twilio');
3
var express = require('express');
4
var router = express.Router();
5
var Property = require('../models/property');
6
var Reservation = require('../models/reservation');
7
var User = require('../models/user');
8
var notifier = require('../lib/notifier');
9
10
// POST: /reservations
11
router.post('/', function (req, res) {
12
var propertyId = req.body.propertyId;
13
var user = req.user;
14
15
Property.findOne({ _id: propertyId })
16
.then(function (property) {
17
var reservation = new Reservation({
18
message: req.body.message,
19
property: propertyId,
20
guest: user.id
21
});
22
23
return reservation.save();
24
})
25
.then(function () {
26
notifier.sendNotification();
27
res.redirect('/properties');
28
})
29
.catch(function(err) {
30
console.log(err);
31
});
32
});
33
34
// POST: /reservations/handle
35
router.post('/handle', twilio.webhook({validate: false}), function (req, res) {
36
var from = req.body.From;
37
var smsRequest = req.body.Body;
38
39
var smsResponse;
40
41
User.findOne({phoneNumber: from})
42
.then(function (host) {
43
return Reservation.findOne({status: 'pending'});
44
})
45
.then(function (reservation) {
46
if (reservation === null) {
47
throw 'No pending reservations';
48
}
49
reservation.status = smsRequest.toLowerCase() === "accept" ? "confirmed" : "rejected";
50
return reservation.save();
51
})
52
.then(function (reservation) {
53
var message = "You have successfully " + reservation.status + " the reservation";
54
respond(res, message);
55
})
56
.catch(function (err) {
57
var message = "Sorry, it looks like you do not have any reservations to respond to";
58
respond(res, message);
59
});
60
});
61
62
var respond = function(res, message) {
63
var messagingResponse = new MessagingResponse();
64
messagingResponse.message({}, message);
65
66
res.type('text/xml');
67
res.send(messagingResponse.toString());
68
}
69
70
module.exports = router;

In the last step, we'll use Twilio's TwiML and instruct Twilio to send SMS messages to the guest.


After updating the reservation status, we must notify the host that they have successfully confirmed or rejected the reservation. If no reservation is found, we send an error message instead.

If a reservation is confirmed or rejected we send an additional SMS to the guest to pass along the news.

We use the verb Message from TwiML to instruct Twilio's server that it should send SMS messages.

Build the TwiML Response

build-the-twiml-response page anchor

routes/reservations.js

1
var MessagingResponse = require('twilio').twiml.MessagingResponse;
2
var twilio = require('twilio');
3
var express = require('express');
4
var router = express.Router();
5
var Property = require('../models/property');
6
var Reservation = require('../models/reservation');
7
var User = require('../models/user');
8
var notifier = require('../lib/notifier');
9
10
// POST: /reservations
11
router.post('/', function (req, res) {
12
var propertyId = req.body.propertyId;
13
var user = req.user;
14
15
Property.findOne({ _id: propertyId })
16
.then(function (property) {
17
var reservation = new Reservation({
18
message: req.body.message,
19
property: propertyId,
20
guest: user.id
21
});
22
23
return reservation.save();
24
})
25
.then(function () {
26
notifier.sendNotification();
27
res.redirect('/properties');
28
})
29
.catch(function(err) {
30
console.log(err);
31
});
32
});
33
34
// POST: /reservations/handle
35
router.post('/handle', twilio.webhook({validate: false}), function (req, res) {
36
var from = req.body.From;
37
var smsRequest = req.body.Body;
38
39
var smsResponse;
40
41
User.findOne({phoneNumber: from})
42
.then(function (host) {
43
return Reservation.findOne({status: 'pending'});
44
})
45
.then(function (reservation) {
46
if (reservation === null) {
47
throw 'No pending reservations';
48
}
49
reservation.status = smsRequest.toLowerCase() === "accept" ? "confirmed" : "rejected";
50
return reservation.save();
51
})
52
.then(function (reservation) {
53
var message = "You have successfully " + reservation.status + " the reservation";
54
respond(res, message);
55
})
56
.catch(function (err) {
57
var message = "Sorry, it looks like you do not have any reservations to respond to";
58
respond(res, message);
59
});
60
});
61
62
var respond = function(res, message) {
63
var messagingResponse = new MessagingResponse();
64
messagingResponse.message({}, message);
65
66
res.type('text/xml');
67
res.send(messagingResponse.toString());
68
}
69
70
module.exports = router;

And that's a wrap! Next let's take a look at other features you might enjoy in your application.


Node.js goes great with a helping of Twilio... let us prove it:

IVR: Phone Tree

You can route callers to the right people and information with an IVR (interactive voice response) system.

Automated Survey

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.