Back

Quick Guide to Implementing Webhooks in Cal.com

Aug 16, 20246 minute read

Introduction

Hey there, fellow JavaScript aficionado! Ready to supercharge your Cal.com integration with webhooks? You're in the right place. Webhooks are the secret sauce that'll keep your user-facing integrations real-time and snappy. Let's dive in and get those events flowing!

Prerequisites

Before we jump into the code, make sure you've got:

  • A Cal.com account (duh!)
  • An API key (you can grab this from your account settings)
  • Node.js environment (you've got this, right?)

Setting Up Webhooks

Alright, let's get our hands dirty. First things first, we need to tell Cal.com where to send those juicy event notifications.

const axios = require('axios'); const createWebhook = async () => { try { const response = await axios.post('https://api.cal.com/v1/webhooks', { subscriberUrl: 'https://your-awesome-app.com/webhook', eventTriggers: ['BOOKING_CREATED', 'BOOKING_RESCHEDULED', 'BOOKING_CANCELLED'], active: true }, { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_API_KEY' } }); console.log('Webhook created:', response.data); } catch (error) { console.error('Error creating webhook:', error.response.data); } }; createWebhook();

Boom! You've just set up a webhook. Cal.com will now ping your endpoint whenever someone books, reschedules, or cancels an appointment.

Webhook Event Types

Cal.com offers a smorgasbord of event types. For user-facing integrations, you'll probably want to focus on:

  • BOOKING_CREATED
  • BOOKING_RESCHEDULED
  • BOOKING_CANCELLED

But hey, don't let me stop you from exploring others if they fit your use case!

Handling Webhook Payloads

When Cal.com sends an event your way, you'll want to process it. Here's a quick Express route to get you started:

const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const { type, payload } = req.body; switch (type) { case 'BOOKING_CREATED': // Handle new booking console.log('New booking:', payload); break; case 'BOOKING_RESCHEDULED': // Handle rescheduled booking console.log('Rescheduled booking:', payload); break; case 'BOOKING_CANCELLED': // Handle cancelled booking console.log('Cancelled booking:', payload); break; default: console.log('Unhandled event type:', type); } res.sendStatus(200); });

Security Considerations

Trust, but verify! Always check that the webhook is legit:

const crypto = require('crypto'); const verifyWebhookSignature = (req, secret) => { const signature = req.headers['cal-signature']; const body = JSON.stringify(req.body); const hmac = crypto.createHmac('sha256', secret); const digest = hmac.update(body).digest('hex'); return signature === digest; }; app.post('/webhook', express.json(), (req, res) => { if (!verifyWebhookSignature(req, 'your_webhook_secret')) { return res.status(401).send('Invalid signature'); } // Process the webhook... });

Error Handling and Retries

Things go wrong. It's a fact of life. Be prepared:

app.post('/webhook', express.json(), async (req, res) => { try { // Process webhook... res.sendStatus(200); } catch (error) { console.error('Error processing webhook:', error); res.status(500).send('Internal Server Error'); // Implement retry logic here } });

Testing Webhooks

Cal.com provides a nifty webhook tester in their dashboard. Use it! But also, set up a local environment with ngrok for thorough testing. Your future self will thank you.

Scaling Considerations

If you're expecting a tsunami of events, consider using a message queue like RabbitMQ or Redis. Process events asynchronously to keep your API snappy:

const queue = require('your-favorite-queue-library'); app.post('/webhook', express.json(), (req, res) => { queue.add(req.body); res.sendStatus(200); }); // In your worker queue.process(async (job) => { // Process the webhook event });

Conclusion

And there you have it! You're now armed with the knowledge to implement webhooks in Cal.com like a pro. Remember, webhooks are powerful, but with great power comes great responsibility. Handle them with care, and they'll serve you well.

Additional Resources

Now go forth and webhook all the things! Happy coding! 🚀