Back

Quick Guide to Implementing Webhooks in Strava

Aug 11, 20245 minute read

Hey there, fellow JavaScript dev! Ready to supercharge your Strava integration with webhooks? Let's dive right in and get those real-time updates flowing!

Introduction

Webhooks are like your app's personal newsfeed for Strava events. Instead of constantly polling the API, Strava gives you a nudge whenever something interesting happens. Cool, right? We'll be using Strava's API v3 to set this up, so buckle up!

Prerequisites

Before we start, make sure you've got:

  • Strava API access (go create an app in your Strava settings if you haven't already)
  • A Node.js environment (you're a JS dev, so I'm sure you've got this covered)
  • An HTTPS-enabled server (Strava's pretty strict about this)

Setting Up the Webhook

First things first, let's create a webhook subscription. Here's how you do it:

const axios = require('axios'); const createSubscription = async () => { try { const response = await axios.post('https://www.strava.com/api/v3/push_subscriptions', { client_id: YOUR_CLIENT_ID, client_secret: YOUR_CLIENT_SECRET, callback_url: 'https://your-server.com/webhook', verify_token: 'SOME_RANDOM_STRING' }); console.log('Subscription created:', response.data); } catch (error) { console.error('Error creating subscription:', error); } }; createSubscription();

Now, Strava's going to try to validate your callback URL. Here's a quick Express.js handler for that:

app.get('/webhook', (req, res) => { const VERIFY_TOKEN = 'SOME_RANDOM_STRING'; const mode = req.query['hub.mode']; const token = req.query['hub.verify_token']; const challenge = req.query['hub.challenge']; if (mode && token) { if (mode === 'subscribe' && token === VERIFY_TOKEN) { console.log('Webhook verified'); res.json({ "hub.challenge": challenge }); } else { res.sendStatus(403); } } });

Receiving Webhook Events

Time to set up your endpoint to catch those sweet, sweet events:

app.post('/webhook', (req, res) => { console.log('Received webhook event:', req.body); // Process the event here res.sendStatus(200); });

Processing Webhook Events

Strava sends different types of events. Here's how you might handle a new activity:

app.post('/webhook', (req, res) => { const event = req.body; if (event.object_type === 'activity' && event.aspect_type === 'create') { console.log(`New activity created by athlete ${event.owner_id}`); // Do something cool with this info! } res.sendStatus(200); });

Error Handling and Best Practices

Always implement retry logic and respect Strava's rate limits. Here's a simple exponential backoff:

const axios = require('axios'); const backoff = require('exponential-backoff'); const fetchWithRetry = async (url) => { return backoff.backOff(() => axios.get(url), { numOfAttempts: 5, startingDelay: 1000, }); };

And don't forget to secure your webhook endpoint! Use HTTPS and validate the incoming requests.

Testing Your Webhook Implementation

Strava provides a handy webhook event simulator in their API settings. Use it to debug and make sure everything's working smoothly.

Conclusion

And there you have it! You're now ready to create some awesome real-time Strava integrations. Remember, the Strava API docs are your best friend for more detailed info.

Happy coding, and may your KOMs be many! 🚴‍♂️💨