No matter what scale app you’re working on, keeping track of user activity is critical to its success. Segment helps you collect data about what your users are doing, then visualize and manipulate that data with integrations for analytics, marketing, and more.

But what if the service you want to share data with doesn’t have a Segment integration? Or you want to route behavioral analytics from Segment into your own database? Webhooks are a great solution for passing your events to data consumers that would ordinarily be out of reach.

What Are Webhooks?

Webhooks are a technique for allowing apps to receive notifications about each other’s events. The technology is simple: when something interesting happens on site A, a request is made to a URL on site B including all of the relevant information about the event. The website IFTTT (“If This Then That”) popularized this technique by allowing users to easily connect a wide range of services: “If Yahoo! Weather says it’s less than 50 degrees outside, post a ‘Brrrr!’ status message on Facebook!”.

Segment allows you to leverage the power of webhooks by designating a URL to receive information about every event it tracks.

For example, at Treeline.io we wanted to receive a message in Slack whenever we received a new user signup. Because Slack doesn’t integrate directly with Segment, we would normally have had to hack together a solution for getting these notifications. But since both Slack and Segment support webhooks, wiring the two together was a breeze. Read on to learn how!

Setting up Webhooks on Segment

This part is super easy—webhooks are listed among the 100+ integrations that Segment offers. Simply click the “Integrations” link from your dashboard, click “Webhooks”, and enter the URL that you’d like Segment to post information to when events come in.

Setting up Your App to Receive Webhook Requests

This is where things get trickier—how do you start listening for those webhook requests from Segment in your server-side app? The specifics vary based on what platform your app is on (Rails, Django, Sails.js, etc.), but there are two basic steps:

  1. Define the route that maps the webhook URL you chose to a handler (often called a controller or action) in your app code.

  2. Write code for that handler which takes the information posted to the webhook URL and does something fun with it.

For security reasons, it’s best to make the webbook route unguessable, but for this example we’ll define it as /segment. Our goal is to post an automated message to one of our Slack channels whenever we receive a track notification from Segment with the event “Signed Up”. Using Sails.js, we’d first create a new route in our config/routes.js file:

“POST /segment”: “WebhookController.receiveEvent”

This maps any request to the /segment URL via HTTP POST to the receiveEventaction in the Webhook controller. Then, in api/controllers/WebhookController.js:

// Import the Slack machinepack
var Slack = require('machinepack-slack');

module.exports = {
  receiveEvent: function(req, res) {

    // If the notification type is "track", and the event is "Signed Up", post to Slack
    if (req.param('type') == 'track' && req.param('event') == 'Signed Up') {

      // Post a message to the specified channel in Slack.
      Slack.postToChannel({
        // Get this URL from your Slack webhook integration screen
        webhookUrl: 'http://hooks.slack.com/services/XYZ12345',
        username: 'myslackuser',
        channel: '#news',
        message: 'User ' + req.param('userId') + ' just signed up!'
      }).exec({
        // An unexpected error occurred.
        error: function(err) {
          return res.serverError(err);
        },
        // Specified subdomain and webhook token combination
        // does not match any known Slack accounts
        notFound: function() {
          return res.notFound();
        },
        // OK.
        success: function() {
          return res.send(200);
        }
      });
    }

    // If the event is not a "track", ignore it
    else {
      return res.send(200);
    }

  }

};

Notice that we’re using the Slack machinepack for Node.js to post to our Slack channel, and that we’ve previously set up our Slack account to accept posts to its own webhook. Now whenever a “Signed Up” event is tracked in Segment, the message “The user { userId } just signed up!” will appear in the #news channel of Slack. 

How Treeline Can Help

Treeline is a new product that lets you create your app’s backend without writing code—just drag and drop different “machines” onto a route, snap them together, and Treeline writes all the code for you. Here’s what the above handler would look like implemented in Treeline:

Webhooks let you take advantage of the power of Segment events by sharing them across multiple apps. We use them at Treeline to help us stay informed of important events—let’s see what you can do!

Hit us up on Twitter @treelinehq with other ideas for using Segment webhooks.