Fongang Rodrique Fongang Rodrique

How to Receive and Replay External Webhooks in Cloudflare with Hookdeck

Published · Updated


Webhooks introduce event-driven integrations between different applications or platforms.

When it comes to building event-driven architectures, it is recommended to introduce an event gateway to manage webhooks for security, routing, log tracing, throttled delivery, and webhook event replay.

In this article, we will explore how to leverage Hookdeck, an event gateway, to replay webhooks for your Cloudflare functions. Hookdeck provides a comprehensive set of features, including security, routing, log tracing, and analytics, to help you effectively manage webhook events.

Setting up a Cloudflare function

To begin, let's set up a Cloudflare function to consume webhook events. Cloudflare Workers allows you to write serverless functions that run on Cloudflare's global edge network, providing fast and scalable execution.

To create a Cloudflare function:

  • Log in to your Cloudflare dashboard.
  • Click on Workers & Pages from the sidebar then Create Application to create a new Worker application.

You can also scaffold a new Worker project locally using the Wrangler CLI: npm create cloudflare@latest -- my-webhook-worker. This generates a project you can develop and test locally with npx wrangler dev before deploying with npx wrangler deploy.

create Cloudflare application

  • In the worker.js file update the boilerplate code and the fetch method to match the example below, which lets you receive and process webhook events in a Cloudflare Worker.

    export default {
      async fetch(request, env, ctx) {
        // Verify that the request method is POST (forwarded by Hookdeck)
        if (request.method !== "POST") {
          return new Response("Invalid request method.", { status: 405 });
        }
    
        // Verify any necessary security measures, such as validating the request origin or adding authentication checks
    
        try {
          // Access the payload of the webhook event
          const payload = await request.text();
    
          // Respond immediately, then process in the background
          ctx.waitUntil(processWebhook(payload));
    
          return new Response("Webhook event processed successfully.", {
            status: 200,
          });
        } catch (error) {
          return new Response("Failed to process webhook event.", {
            status: 500,
          });
        }
      },
    };
    
    async function processWebhook(payload) {
      // Perform any heavy processing here (API calls, database writes, etc.)
      // This runs for up to 30 seconds after the response is sent
      console.log(payload);
    }
    

You can customize this function based on your specific requirements. It's important to handle errors accordingly and return appropriate status codes to indicate success or failure. This is crucial when replaying webhook events, which we will see later.

The code above uses ctx.waitUntil() to respond to the webhook sender immediately while continuing to process the payload in the background for up to 30 seconds. This is the recommended pattern for webhook handlers in Cloudflare Workers — it prevents timeouts from the webhook source while giving you time to complete processing.

CPU time limits: The free Workers plan allows 10ms of CPU time per request, which is enough for simple webhook handlers. For handlers that need to verify signatures, parse large payloads, or make outbound API calls, the paid plan ($5/month) provides 30 seconds of CPU time. Note that time spent waiting on network I/O (fetch calls, database queries) does not count toward CPU time.

  • Save and deploy the worker and take note of its URL.

save and deploy Cloudflare

If your webhook source supports signature verification (e.g., GitHub's X-Hub-Signature-256 or Stripe's Stripe-Signature), use Workers' built-in Web Crypto API (crypto.subtle.verify()) for timing-safe HMAC validation. This is more secure than string comparison and runs natively in the Workers runtime. Store your webhook secret using wrangler secret put so it's encrypted and accessible via the env parameter.

Replay webhooks

Using Hookdeck as a gateway between your source platform webhooks to Cloudflare, you can replay any failed event that doesn’t make it to Cloudflare.

Follow the steps below to achieve that.

Create a Hookdeck connection

  • Sign up or log in to your Hookdeck dashboard.
  • Click on Connections on the side panel then Create + a new connection. This opens a right sidebar; fill in the required information and Save.
    • Source: Specify the source to be any platform or application you want to receive webhooks from.
    • Destination: Create a destination pointing to the URL of your Cloudflare function.

create destination cloudflare url

After creating the connection, you are given a URL to use on the source platform.

The created connection makes it possible for webhook events from your source to be relayed directly to Cloudflare.

Receiving webhook events

You can utilize Hookdeck Console to simulate example webhooks from popular webhook sources.

Say for example your webhook source is GitHub. When an event is triggered, it can be seen on the Hookdeck dashboard and also monitored on Cloudflare Logs.

From your Hookdeck dashboard, switch to the Events tab from the side panel and filter as per the connection created above. This shows the activities of events on that connection.

Cloudflare event activities

From your Cloudflare dashboard, switch to Worker & Pages and select the Worker function deployed above to open. Click on the Logs tab and Begin log stream to capture and see any incoming event in real time.

Cloudflare begin log stream

Replaying error or failed webhooks

In case any failed events occur and the Cloudflare worker function doesn’t execute properly, Hookdeck makes it possible for such an event to still be replayed from the Hookdeck event panel.

Click on the kebab menu across the failed event and Retry. This attempts sending the event to your destination again.

Retry Cloudflare webhook

You now know how to replay webhook events for your Cloudflare functions using Hookdeck. By leveraging Hookdeck's powerful features, such as security, routing, and analytics, you can effectively manage and troubleshoot webhook events from third-party platforms. Take a look at Hookdeck's documentation to explore more.


Fongang Rodrique

Fongang Rodrique

Lead Software Developer

Rodrique is a technical writer and developer with expertise in webhook who has authored documentation for many tech companies such as Rocket.chat