Cloudflare Workers

Build a Cloudflare Worker Webhook Receiver

A practical Cloudflare Worker webhook receiver with JSON validation, a dedicated secret, fast responses and backend forwarding.

Illustration of a bot debugging API and connection errors
Illustration: a webhook receiver should validate first, then hand clean data to the rest of the system.

A practical Cloudflare Worker webhook receiver with JSON validation, a dedicated secret, fast responses and backend forwarding.

Updated 2026-09-06Cloudflare WorkersPractical guide2 min read

In plain English

This guide uses a Cloudflare Worker as event-driven web code. It is best thought of as a small serverless endpoint, not as a normal PC left running 24/7.

serverlessWorker Secretrequestresponse

Why use a Worker at the public edge?

A Worker can give you a small public HTTPS endpoint without exposing the IP address or port of a VPS. It is a good place for cheap checks: method, path, secret, JSON schema, duplicate key format and basic rate control.

Minimal receiver

export default {
  async fetch(request, env) {
    if (request.method !== "POST") {
      return new Response("Method not allowed", { status: 405 });
    }

    let data;
    try { data = await request.json(); }
    catch { return Response.json({ok:false,error:"invalid_json"},{status:400}); }

    if (data.token !== env.WEBHOOK_TOKEN) {
      return Response.json({ok:false,error:"unauthorized"},{status:401});
    }

    if (!data.event_id || !data.symbol || !["buy","sell","close"].includes(data.action)) {
      return Response.json({ok:false,error:"invalid_event"},{status:422});
    }

    const upstream = await fetch(env.BACKEND_URL, {
      method: "POST",
      headers: {"content-type":"application/json", "x-edge-token": env.EDGE_TOKEN},
      body: JSON.stringify(data)
    });

    return Response.json({ok: upstream.ok}, {status: upstream.ok ? 200 : 502});
  }
}

Secrets belong in bindings, not code

WEBHOOK_TOKEN, EDGE_TOKEN and private backend URLs should be configuration/secrets. Static HTML files are public. Worker source may also end up in repositories, screenshots or backups.

Static site and Worker API can coexist

Cloudflare's current Workers Static Assets model can serve HTML/CSS files while a Worker script handles selected API routes. For a documentation site plus webhooks, that makes it possible to keep / static and use something like /api/webhook for logic.

Do not forward blindly. The Worker should reject malformed events before they reach the private backend. The backend must still validate again because edge checks are defense in depth, not a substitute for backend checks.

Before you rely on this in production

  • Secrets use Worker secret storage.
  • CORS is limited to required origins where relevant.
  • Backend calls have clear timeout/error handling.
  • The Worker returns intentional status codes.