Skip to main content

Best Practices for Webhooks

Webhooks are HTTP endpoints that you register with a system, allowing that system to inform your application about events by sending HTTP POST requests with event information in the body.

Developers register their applications' webhook endpoints with Scalekit to listen to events from the directory providers of their enterprise customers. Here are some common best practices developers follow to ensure their apps are secure and performant:

Subscribe Only to Relevant Events

While you can listen to all events from Scalekit, it's best to subscribe only to the events your app needs. This approach has several benefits:

  • Your app doesn't have to process every event
  • You can avoid overloading a single execution context by handling every event type

Verify Webhook Signatures

Scalekit sends POST requests to your registered webhook endpoint. To ensure the request is coming from Scalekit and not a malicious actor, you should verify the request using the Signing Secret found in the Scalekit Dashboard > Webhook > Any Endpoint.

Here's an example of how to verify webhooks using the Svix library:

Webhook Signature Verification
app.post('/webhook', async (req, res) => {
  // Parse the JSON body of the request
  const event = await req.json();

  // Get headers from the request
  const headers = req.headers;

  // Secret from Scalekit Dasbhoard > Webhooks
  const secret = process.env.SCALEKIT_WEBHOOK_SECRET;

  try {
    // Verify the webhook payload using the secret, headers, and event data
    await scalekit.verifyWebhookPayload(secret, headers, event);
  } catch (error) {
    // Return a 400 response if the signature is invalid
    res.status(400).json({ error: 'Invalid signature' });
  }
});

Check the Event Type Before Processing

Make sure to check the event.type before consuming the data received by the webhook endpoint. This ensures that your application relies on accurate information, even if more events are added in the future.

app.post('/webhook', async (req, res) => {
  const event = req.body;

  if (event.type === 'scalekit.dir.user.create') {
    const { email, name } = event.data;
    await createUserAccount(email, name);
  }

  res.status(201).json({ status: 201 });
});

async function createUserAccount(email, name) {
  // Implement your user creation logic
}

Avoid Webhook Timeouts

To avoid unnecessary timeouts, respond to the webhook trigger with a response code of 201 and process the event asynchronously.

By following these best practices, you can ensure that your application effectively handles events from Scalekit, maintaining optimal performance and security.


Is this page helpful? Yes No