How to create a webhook using Node, Express and Ngrok

Here is a quick example of how to subscribe to a webhook with a dummy server using a Mac

Step 1

Log in or create a Strava account. After it has been created, click here to set up an App.

Step 2

Sign up for a free ngrok account. We are using homebrew to install ngrok, install it here.

Open a terminal and run:

brew cask install ngrok

Once you’ve installed ngrok, you will need to install your authtoken. To find YOUR_TOKEN, go to your ngrok dashboard.

In terminal, run:

ngrok authtoken YOUR_TOKEN

If this is confusing, please refer to ngrok’s documentation.

Step 3

Create a new Node.js project in terminal:

mkdir strava-webhooks
cd strava-webhooks
touch index.js 
npm init
npm install express body-parser --save

Step 4

This is is the code to run a dummy server that will help you complete a webhook subscription. It will not process webhook events for you. Please copy/paste the below into index.js:

'use strict';

// Imports dependencies and sets up http server
const
  express = require('express'),
  bodyParser = require('body-parser'),
// creates express http server
  app = express().use(bodyParser.json());

// Sets server port and logs message on success
app.listen(process.env.PORT || 80, () => console.log('webhook is listening'));

// Creates the endpoint for our webhook
app.post('/webhook', (req, res) => {
  console.log("webhook event received!", req.query, req.body);
  res.status(200).send('EVENT_RECEIVED');
});

// Adds support for GET requests to our webhook
app.get('/webhook', (req, res) => {
  // Your verify token. Should be a random string.
  const VERIFY_TOKEN = "STRAVA";
  // Parses the query params
  let mode = req.query['hub.mode'];
  let token = req.query['hub.verify_token'];
  let challenge = req.query['hub.challenge'];
  // Checks if a token and mode is in the query string of the request
  if (mode && token) {
    // Verifies that the mode and token sent are valid
    if (mode === 'subscribe' && token === VERIFY_TOKEN) {     
      // Responds with the challenge token from the request
      console.log('WEBHOOK_VERIFIED');
      res.json({"hub.challenge":challenge});  
    } else {
      // Responds with '403 Forbidden' if verify tokens do not match
      res.sendStatus(403);      
    }
  }
});

Step 5

Start the node server by running the following in terminal:

node index.js

Step 6

Open a new tab and start ngrok so your local server is reachable by internet:

ngrok http 80

Step 7

Now make a Postman or cURL request to subscribe to a webhook.

Please change the parameters as the following is dummy data:

curl -X POST \
  https://api.strava.com/api/v3/push_subscriptions \
  -F client_id=12345 \
  -F client_secret=1234567abcdefg \
  -F callback_url=https://1234abcd.ngrok.io/webhook \
  -F verify_token=STRAVA

Step 8

If your webhook subscription worked, great! If not, go through the steps and double check again.