Skip to main content

x402 on Cloudflare Workers

A tiny Worker that returns HTTP 402 challenges. Deploy globally in seconds - Cloudflare Workers run at the edge with zero cold starts.

Minimal Worker

export default {
  async fetch(req) {
    const url = new URL(req.url);

    if (url.pathname === "/priced") {
      // TODO: verify receipt
      const paid = false;

      if (!paid) {
        return new Response(JSON.stringify({
          detail: "Payment required to access /priced",
          payment: {
            protocol: "x402",
            amount: "0.05",
            currency: "USDC",
            reference: "cfw-001"
          }
        }), {
          status: 402,
          headers: { "content-type": "application/json" }
        });
      }

      return Response.json({ ok: true, data: "worker-secret" });
    }

    return new Response("Not found", { status: 404 });
  }
};
Performance note
Workers respond in milliseconds from 300+ global locations. Perfect for high-volume 402 challenges that need low latency.

Adding receipt verification

When a client retries with a receipt, verify it using the Web Crypto API (available in Workers):

export default {
  async fetch(req) {
    const url = new URL(req.url);

    if (url.pathname === "/priced") {
      const receipt = req.headers.get("x-receipt");

      if (!receipt) {
        return new Response(JSON.stringify({
          detail: "Payment required to access /priced",
          payment: {
            protocol: "x402",
            amount: "0.05",
            currency: "USDC",
            reference: "cfw-001"
          }
        }), {
          status: 402,
          headers: { "content-type": "application/json" }
        });
      }

      // Verify receipt with Web Crypto API
      const verified = await verifyReceipt(receipt);

      if (!verified) {
        return Response.json(
          { error: "Invalid or expired receipt" },
          { status: 403 }
        );
      }

      return Response.json({ ok: true, data: "worker-secret" });
    }

    return new Response("Not found", { status: 404 });
  }
};

Worker features for x402

Deployment

Deploy with Wrangler CLI:

npx wrangler deploy

Next steps

Integrate with your payment rail and deploy to Cloudflare’s global network. See the x402 pillar guide for receipt patterns and verification tips.

Developer Tools