Sending Text Messages with MongoDB Stitch & Twilio

Andrew Morgan

Technical, Cloud
Facebook ShareLinkedin ShareReddit ShareTwitter Share

When creating a well-rounded app, there are lots of table stakes features that make the app more useful but have already been implemented thousands of times before. Having the application backend send a text message informing your customer of an event is a classic example of such a “commodity” feature.

Think about using a website or app to book a taxi, where you give your phone number so that you get sent a text message when the taxi’s on its way. Why would the writers of that taxi app want to waste time writing text messaging code? There’s nothing extra they can do to differentiate it from other apps – so why not just consume it as a service from something like Twilio?

MongoDB Stitch makes it even less work to add this kind of feature. Rather than standing up an app server, figuring out how to use the Twilio API, writing the code, and possibly creating a REST API, just configure the Twilio service in Stitch.

Using MongoDB Stitch to send SMS text messages via Twilio

When configuring the Stitch Twilio serving, you supply the Account ID and Auth Token from your Twilio account. All that's left is to write the Stitch function to invoke the service:

exports = function(trip, user){
  const twilio = context.services.get("twilio");

  twilio.send({
    to: user.phone,
    from: context.values.get("twilioNumber"),
    body: "Hi " 
      + user.firstname 
      + " - just to let you know that your taxi to " 
      + trip.destination + " will be with you at " 
      + trip.pickupTime + "."
  });
};

You can also have your application react when receiving a text message by configuring incoming webhooks for the Twilio service.

Creating your first Stitch app? Start with one of the Stitch tutorials.

Want to learn more about MongoDB Stitch? Read the white paper.