Skip to contentSkip to navigationSkip to topbar
On this page

Masked Phone Numbers with Node.js and Express


This Express(link takes you to an external page) sample application is modeled after the amazing rental experience created by AirBnB(link takes you to an external page), but with more Klingons(link takes you to an external page).

Host users can offer rental properties which other guest users can reserve. The guest and the host can then anonymously communicate via a disposable Twilio phone number created just for a reservation. In this tutorial, we'll show you the key bits of code to make this work.

To run this sample app yourself, download the code and follow the instructions on GitHub(link takes you to an external page).

(warning)

Legal implications of managing communications between users

If you choose to manage communications between your users, including voice calls, text-based messages (e.g., SMS), and chat, you may need to comply with certain laws and regulations, including those regarding obtaining consent. Additional information regarding legal compliance considerations and best practices for using Twilio to manage and record communications between your users, such as when using Twilio Proxy, can be found here(link takes you to an external page).

Notice: Twilio recommends that you consult with your legal counsel to make sure that you are complying with all applicable laws in connection with communications you record or store using Twilio.

Read how Lyft uses masked phone numbers to let customers securely contact drivers.(link takes you to an external page)


Create a Reservation

create-a-reservation page anchor

The first step in connecting a guest and host is creating a reservation. Here we handle a form submission for a new reservation which contains the message and the guest's information which is grabbed from the logged in user.

Create a Reservation

create-a-reservation-1 page anchor

routes/reservations.js

1
var twilio = require('twilio');
2
var MessagingResponse = require('twilio').twiml.MessagingResponse;
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
var purchaser = require('../lib/purchaser');
10
var middleware = require('../lib/middleware');
11
12
router.get('/', middleware.isAuthenticated, function (req, res) {
13
var userId = req.user.id;
14
Reservation.find({})
15
.deepPopulate('property property.owner guest')
16
.then(function (reservations) {
17
var hostReservations = reservations.filter(function (reservation) {
18
return reservation.property.owner.id === userId;
19
});
20
21
res.render('reservations/index', { reservations: hostReservations, user: req.user });
22
});
23
});
24
25
// POST: /reservations
26
router.post('/', function (req, res) {
27
var propertyId = req.body.propertyId;
28
var user = req.user;
29
30
Property.findOne({ _id: propertyId })
31
.then(function (property) {
32
var reservation = new Reservation({
33
message: req.body.message,
34
property: propertyId,
35
guest: user.id
36
});
37
38
return reservation.save();
39
})
40
.then(function () {
41
notifier.sendNotification();
42
res.redirect('/properties');
43
})
44
.catch(function(err) {
45
console.log(err);
46
});
47
});
48
49
// POST: /reservations/handle
50
router.post('/handle', twilio.webhook({validate: false}), function (req, res) {
51
var from = req.body.From;
52
var smsRequest = req.body.Body;
53
54
var smsResponse;
55
56
User.findOne({phoneNumber: from})
57
.then(function (host) {
58
return Reservation.findOne({status: 'pending'})
59
.deepPopulate('property property.owner guest')
60
})
61
.then(function (reservation) {
62
if (reservation === null) {
63
throw 'No pending reservations';
64
}
65
66
var hostAreaCode = reservation.property.owner.areaCode;
67
68
var phoneNumber = purchaser.purchase(hostAreaCode);
69
var reservationPromise = Promise.resolve(reservation);
70
71
return Promise.all([phoneNumber, reservationPromise]);
72
})
73
.then(function (data) {
74
var phoneNumber = data[0];
75
var reservation = data[1];
76
77
if (isSmsRequestAccepted(smsRequest)) {
78
reservation.status = "confirmed";
79
reservation.phoneNumber = phoneNumber;
80
} else {
81
reservation.status = "rejected";
82
}
83
return reservation.save();
84
})
85
.then(function (reservation) {
86
var message = "You have successfully " + reservation.status + " the reservation";
87
respond(res, message);
88
})
89
.catch(function (err) {
90
console.log(err);
91
var message = "Sorry, it looks like you do not have any reservations to respond to";
92
respond(res, message);
93
});
94
});
95
96
var isSmsRequestAccepted = function (smsRequest) {
97
return smsRequest.toLowerCase() === 'accept';
98
};
99
100
var respond = function(res, message) {
101
var messagingResponse = new MessagingResponse();
102
messagingResponse.message(message);
103
104
res.type('text/xml');
105
res.send(messagingResponse.toString());
106
}
107
108
module.exports = router;

Part of our reservation system is receiving reservation requests from potential renters. However, these reservations need to be confirmed. Let's see how we would handle this step.


Before the reservation is finalized, the host needs to confirm that the property was reserved. Learn how to automate this process in our first AirTNG tutorial, Workflow Automation(link takes you to an external page).

routes/reservations.js

1
var twilio = require('twilio');
2
var MessagingResponse = require('twilio').twiml.MessagingResponse;
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
var purchaser = require('../lib/purchaser');
10
var middleware = require('../lib/middleware');
11
12
router.get('/', middleware.isAuthenticated, function (req, res) {
13
var userId = req.user.id;
14
Reservation.find({})
15
.deepPopulate('property property.owner guest')
16
.then(function (reservations) {
17
var hostReservations = reservations.filter(function (reservation) {
18
return reservation.property.owner.id === userId;
19
});
20
21
res.render('reservations/index', { reservations: hostReservations, user: req.user });
22
});
23
});
24
25
// POST: /reservations
26
router.post('/', function (req, res) {
27
var propertyId = req.body.propertyId;
28
var user = req.user;
29
30
Property.findOne({ _id: propertyId })
31
.then(function (property) {
32
var reservation = new Reservation({
33
message: req.body.message,
34
property: propertyId,
35
guest: user.id
36
});
37
38
return reservation.save();
39
})
40
.then(function () {
41
notifier.sendNotification();
42
res.redirect('/properties');
43
})
44
.catch(function(err) {
45
console.log(err);
46
});
47
});
48
49
// POST: /reservations/handle
50
router.post('/handle', twilio.webhook({validate: false}), function (req, res) {
51
var from = req.body.From;
52
var smsRequest = req.body.Body;
53
54
var smsResponse;
55
56
User.findOne({phoneNumber: from})
57
.then(function (host) {
58
return Reservation.findOne({status: 'pending'})
59
.deepPopulate('property property.owner guest')
60
})
61
.then(function (reservation) {
62
if (reservation === null) {
63
throw 'No pending reservations';
64
}
65
66
var hostAreaCode = reservation.property.owner.areaCode;
67
68
var phoneNumber = purchaser.purchase(hostAreaCode);
69
var reservationPromise = Promise.resolve(reservation);
70
71
return Promise.all([phoneNumber, reservationPromise]);
72
})
73
.then(function (data) {
74
var phoneNumber = data[0];
75
var reservation = data[1];
76
77
if (isSmsRequestAccepted(smsRequest)) {
78
reservation.status = "confirmed";
79
reservation.phoneNumber = phoneNumber;
80
} else {
81
reservation.status = "rejected";
82
}
83
return reservation.save();
84
})
85
.then(function (reservation) {
86
var message = "You have successfully " + reservation.status + " the reservation";
87
respond(res, message);
88
})
89
.catch(function (err) {
90
console.log(err);
91
var message = "Sorry, it looks like you do not have any reservations to respond to";
92
respond(res, message);
93
});
94
});
95
96
var isSmsRequestAccepted = function (smsRequest) {
97
return smsRequest.toLowerCase() === 'accept';
98
};
99
100
var respond = function(res, message) {
101
var messagingResponse = new MessagingResponse();
102
messagingResponse.message(message);
103
104
res.type('text/xml');
105
res.send(messagingResponse.toString());
106
}
107
108
module.exports = router;

Once the reservation is confirmed, we need to purchase a Twilio number that the guest and host can use to communicate.


Purchase a Twilio Number

purchase-a-twilio-number page anchor

Here we use a Twilio Node Helper Library(link takes you to an external page) to search for and buy a new phone number to associate with the reservation. When we buy the number, we designate a Twilio Application that will handle webhook(link takes you to an external page) requests when the new number receives an incoming call or text.

We then save the new phone number on our reservation model, so when our app receives calls or texts to this number, we'll know which reservation the call or text belongs to.

lib/purchaser.js

1
var config = require('../config');
2
var client = require('twilio')(config.accountSid, config.authToken);
3
4
var purchase = function (areaCode) {
5
var phoneNumber;
6
7
return client.availablePhoneNumbers('US').local.list({
8
areaCode: areaCode,
9
voiceEnabled: true,
10
smsEnabled: true
11
}).then(function(searchResults) {
12
if (searchResults.availablePhoneNumbers.length === 0) {
13
throw { message: 'No numbers found with that area code' };
14
}
15
16
return client.incomingPhoneNumbers.create({
17
phoneNumber: searchResults.availablePhoneNumbers[0].phoneNumber,
18
voiceApplicationSid: config.applicationSid,
19
smsApplicationSid: config.applicationSid
20
});
21
}).then(function(number) {
22
return number.phone_number;
23
});
24
}
25
26
exports.purchase = purchase;

Now that each reservation has a Twilio Phone Number, we can see how the application will look up reservations as guest or host calls come in.


When someone sends an SMS or calls one of the Twilio numbers you have configured, Twilio makes a request to the URL you set in the TwiML app. In this request, Twilio includes some useful information including:

  • The From number that originally called or sent an SMS.
  • The To Twilio number that triggered this request.

Take a look at Twilio's SMS Documentation and Twilio's Voice Documentation for a full list of the parameters you can use.

In our controller we use the to parameter sent by Twilio to find a reservation that has the number we bought stored in it, as this is the number both hosts and guests will call and send SMS to.

routes/commuter.js

1
var twilio = require('twilio');
2
var VoiceResponse = require('twilio').twiml.VoiceResponse;
3
var MessagingResponse = require('twilio').twiml.MessagingResponse;
4
var express = require('express');
5
var router = express.Router();
6
var Reservation = require('../models/reservation');
7
8
// POST: /commuter/use-sms
9
router.post('/use-sms', twilio.webhook({ validate: false }), function (req, res) {
10
from = req.body.From;
11
to = req.body.To;
12
body = req.body.Body;
13
14
gatherOutgoingNumber(from, to)
15
.then(function (outgoingPhoneNumber) {
16
var messagingResponse = new MessagingResponse();
17
messagingResponse.message({ to: outgoingPhoneNumber }, body);
18
19
res.type('text/xml');
20
res.send(messagingResponse.toString());
21
})
22
});
23
24
// POST: /commuter/use-voice
25
router.post('/use-voice', twilio.webhook({ validate: false }), function (req, res) {
26
from = req.body.From;
27
to = req.body.To;
28
body = req.body.Body;
29
30
gatherOutgoingNumber(from, to)
31
.then(function (outgoingPhoneNumber) {
32
var voiceResponse = new VoiceResponse();
33
voiceResponse.play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');
34
voiceResponse.dial(outgoingPhoneNumber);
35
36
res.type('text/xml');
37
res.send(voiceResponse.toString());
38
})
39
});
40
41
var gatherOutgoingNumber = function (incomingPhoneNumber, anonymousPhoneNumber) {
42
var phoneNumber = anonymousPhoneNumber;
43
44
return Reservation.findOne({ phoneNumber: phoneNumber })
45
.deepPopulate('property property.owner guest')
46
.then(function (reservation) {
47
var hostPhoneNumber = formattedPhoneNumber(reservation.property.owner);
48
var guestPhoneNumber = formattedPhoneNumber(reservation.guest);
49
50
// Connect from Guest to Host
51
if (guestPhoneNumber === incomingPhoneNumber) {
52
outgoingPhoneNumber = hostPhoneNumber;
53
}
54
55
// Connect from Host to Guest
56
if (hostPhoneNumber === incomingPhoneNumber) {
57
outgoingPhoneNumber = guestPhoneNumber;
58
}
59
60
return outgoingPhoneNumber;
61
})
62
.catch(function (err) {
63
console.log(err);
64
});
65
}
66
67
var formattedPhoneNumber = function(user) {
68
return "+" + user.countryCode + user.areaCode + user.phoneNumber;
69
};
70
71
module.exports = router;

Next, let's see how to connect the guest and the host via SMS.


Our Twilio application should be configured to send HTTP requests to this controller method on any incoming text message. Our app responds with TwiML to tell Twilio what to do in response to the message.

If the initial message sent to the anonymous number was sent by the host, we forward it on to the guest. Conversely, if the original message was sent by the guest, we forward it to the host.

To find the outgoing number we'll use the gatherOutgoingNumber helper method.

routes/commuter.js

1
var twilio = require('twilio');
2
var VoiceResponse = require('twilio').twiml.VoiceResponse;
3
var MessagingResponse = require('twilio').twiml.MessagingResponse;
4
var express = require('express');
5
var router = express.Router();
6
var Reservation = require('../models/reservation');
7
8
// POST: /commuter/use-sms
9
router.post('/use-sms', twilio.webhook({ validate: false }), function (req, res) {
10
from = req.body.From;
11
to = req.body.To;
12
body = req.body.Body;
13
14
gatherOutgoingNumber(from, to)
15
.then(function (outgoingPhoneNumber) {
16
var messagingResponse = new MessagingResponse();
17
messagingResponse.message({ to: outgoingPhoneNumber }, body);
18
19
res.type('text/xml');
20
res.send(messagingResponse.toString());
21
})
22
});
23
24
// POST: /commuter/use-voice
25
router.post('/use-voice', twilio.webhook({ validate: false }), function (req, res) {
26
from = req.body.From;
27
to = req.body.To;
28
body = req.body.Body;
29
30
gatherOutgoingNumber(from, to)
31
.then(function (outgoingPhoneNumber) {
32
var voiceResponse = new VoiceResponse();
33
voiceResponse.play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');
34
voiceResponse.dial(outgoingPhoneNumber);
35
36
res.type('text/xml');
37
res.send(voiceResponse.toString());
38
})
39
});
40
41
var gatherOutgoingNumber = function (incomingPhoneNumber, anonymousPhoneNumber) {
42
var phoneNumber = anonymousPhoneNumber;
43
44
return Reservation.findOne({ phoneNumber: phoneNumber })
45
.deepPopulate('property property.owner guest')
46
.then(function (reservation) {
47
var hostPhoneNumber = formattedPhoneNumber(reservation.property.owner);
48
var guestPhoneNumber = formattedPhoneNumber(reservation.guest);
49
50
// Connect from Guest to Host
51
if (guestPhoneNumber === incomingPhoneNumber) {
52
outgoingPhoneNumber = hostPhoneNumber;
53
}
54
55
// Connect from Host to Guest
56
if (hostPhoneNumber === incomingPhoneNumber) {
57
outgoingPhoneNumber = guestPhoneNumber;
58
}
59
60
return outgoingPhoneNumber;
61
})
62
.catch(function (err) {
63
console.log(err);
64
});
65
}
66
67
var formattedPhoneNumber = function(user) {
68
return "+" + user.countryCode + user.areaCode + user.phoneNumber;
69
};
70
71
module.exports = router;

Let's see how to connect the guest and the host via phone call next.

That's it! We've just implemented anonymous communications that allow your customers to connect while protecting their privacy.


If you're a Node.js developer working with Twilio, you might want to check out these other tutorials:

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. Learn how to create your own survey in the language and framework of your choice.

Did this help?

did-this-help page anchor

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio(link takes you to an external page) to let us know what you think.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.