Navigation

Create Server-side Functions & Webhooks

You can run server-side functions in response to events in external applications by having those applications call incoming webhooks. Information about each event can be included in the HTTP request used to trigger a webhook and processed in the webhook function.

Respond to a Webhook

Some services allow you to call back to your server with a webhook. One such service is Twilio, which can be set up to forward any text messages it receives to your application by sending a POST request to your webhook URL.

In the following example, you can add a message to a message board by sending a text message to a Twilio phone number. You can also look up any messages you’ve sent by phone number. Twilio encodes information about each message into a request that it sends to the webhook url. When the webhook receives the request, it runs the textMessageHandler function which stores the message in MongoDB.

textMessageHandler webhook function
exports = function(payload, response) {
  // Parse the webhook payload
  let [action, ...messageParts] = payload.Body.split(" ");
  action = action.toLowerCase();
  const message = messageParts.join(" ");

  // Connect to MongoDB Atlas
  const atlas = context.services.get("mongodb-atlas");
  const todos = atlas.db("quickstart").collection("messages");

  // Respond to the webhook payload
  if (message.length > 50) {
    response.setBody("Message is too long. Must be 50 characters or fewer.");
  }
  else if (action === "add") {
    formatPhoneNumber(payload.From)
      .then(fromPhone => {
        return todos.updateOne(
          { "phoneNumber": fromPhone },
          { "$push": { "messages": message } },
          {  "upsert": true }
        );
      })
     .then(() => response.setBody("Successfully added your message!"));
  }
  else {
    let error = `Couldn't process action of type: ${action}. `;
    let advice = 'If you want to add a message, start your message with the word "add".';
    response.setBody(error + advice);
  }
  response.setStatusCode(201);
  response.addHeader("Content-Type", "text/plain");
};

// Twilio expects phone numbers to have a particular format (e.164).
// This function uses a Twilio API to format submitted phone numbers.
function formatPhoneNumber(number) {
  const formattedNumberPromise = context
    .functions
    .execute("lookupPhoneNumber", number)
    .then(response => EJSON.parse(response.body.text()).phone_number);
  return formattedNumberPromise;
}

Live Example

Try to send a message longer than 50 characters. You should receive a response text message informing you that your message is too long.