The AppGini Blog
A few tips and tricks to make your coding life a tiny bit better.

Build a Free Cloudflare Traffic Alert Worker with a PHP Webhook

A sudden traffic spike can be good news—or a sign that a bot discovered your website and invited several thousand of its closest friends. This tutorial creates a small Cloudflare Worker that checks recent request volume every five minutes and calls a webhook on your own website when traffic exceeds a threshold.

It uses Cloudflare Workers, the Cloudflare GraphQL Analytics API, and a simple PHP receiver. A paid Cloudflare subscription is not required: Cloudflare lists httpRequestsAdaptiveGroups as an essential GraphQL analytics dataset available across plans, and the Workers Free plan includes Cron Triggers and sufficient limits for a lightweight scheduled monitor such as this one.

What you will build

The finished workflow looks like this:

  1. A Cloudflare Worker runs every five minutes.
  2. It asks Cloudflare Analytics for the number of HTTP requests during the preceding five minutes.
  3. If the request count is above your chosen threshold, it sends a signed JSON POST request to a URL you control.
  4. Your PHP endpoint verifies the signature and performs the alert action you choose.

Cloudflare Cron Triggers invoke a Worker’s scheduled() handler, and cron schedules use UTC.

Cloudflare Worker traffic alert diagram

Prerequisites

  • A Cloudflare account and an active zone: Add your domain to Cloudflare and ensure its traffic passes through Cloudflare.
  • Node.js: Install the current LTS release from the official Node.js installer; Wrangler requires Node.js 16.17.0 or later.
  • A terminal: PowerShell, Terminal, or a similar command-line application.
  • A PHP-enabled website: Create a small PHP file at a private or difficult-to-guess URL on a site you control (we’ll create a simple example below).

1. Create the Worker project

Run the following commands in a terminal:

1
2
npm create cloudflare@latest -- traffic-threshold-alert
cd traffic-threshold-alert

When prompted, choose a Worker-only project using JavaScript. If the setup tool did not install packages automatically, run:

1
npm install

Cloudflare’s project generator creates a Worker project with files including src/index.js and wrangler.jsonc.

2. Add the five-minute schedule

Open wrangler.jsonc and add the triggers section to the existing configuration. Do not replace the entire file unless you enjoy configuration archaeology.

{
  "triggers": {
    "crons": [
      "*/5 * * * *"
    ]
  },

  "secrets": {
    "required": [
      "CLOUDFLARE_API_TOKEN",
      "ALERT_WEBHOOK_SECRET"
    ]
  }
}

The cron expression */5 * * * * means “run every five minutes.” Declaring required secrets also lets Wrangler stop a deployment if a required secret has not been configured.

3. Create a least-privilege Analytics API token

In the Cloudflare dashboard:

  1. Open Profile → API Tokens.

  2. Select Create Token.

  3. Choose Custom token.

  4. Add this permission:

    1
    
    Account → Account Analytics → Read
    
  5. Under Zone Resources, include the specific zone you intend to monitor.

  6. Create the token and copy it immediately (you will not be able to view it again).

Cloudflare recommends API Tokens rather than Global API Keys because tokens can be restricted to the required permissions and resources. For GraphQL Analytics access, Cloudflare’s current token guidance uses Account → Account Analytics → Read, with zone resources scoped to the relevant zone or zones.

4. Add Worker secrets

Store the API token in Cloudflare as a Worker secret:

1
npx wrangler secret put CLOUDFLARE_API_TOKEN

Next, generate a long random webhook secret:

1
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Copy the generated value, then save it as the second Worker secret:

1
npx wrangler secret put ALERT_WEBHOOK_SECRET

Use the same webhook secret in the PHP endpoint later. Never place API tokens or shared secrets directly in src/index.js, wrangler.jsonc, or a Git repository.

5. Add the Worker code

Open src/index.js and replace its contents with the following code.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
const ZONE_TAG = "YOUR_CLOUDFLARE_ZONE_ID";
const REQUEST_THRESHOLD = 1000;
const WEBHOOK_URL = "https://example.com/private/traffic-alert.php";

function buildGraphQLQuery(start, end) {
  return `
query {
  viewer {
    zones(limit: 1, filter: { zoneTag: "${ZONE_TAG}" }) {
      httpRequestsAdaptiveGroups(
        limit: 1
        filter: {
          datetime_geq: "${start.toISOString()}",
          datetime_lt: "${end.toISOString()}"
        }
      ) {
        count
      }
    }
  }
}
`;
}

async function getRecentRequestCount(env) {
  const end = new Date();
  const start = new Date(end.getTime() - 5 * 60 * 1000);

  const response = await fetch(
    "https://api.cloudflare.com/client/v4/graphql",
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        query: buildGraphQLQuery(start, end),
      }),
    },
  );

  const data = await response.json();

  if (!response.ok || data.errors) {
    console.error("Cloudflare GraphQL error:", JSON.stringify(data));
    throw new Error("Cloudflare GraphQL query failed");
  }

  return (
    data.data?.viewer?.zones?.[0]?.httpRequestsAdaptiveGroups?.[0]?.count ?? 0
  );
}

async function sendWebhookAlert(env, requests) {
  const payload = {
    event: "traffic_threshold_exceeded",
    zone: ZONE_TAG,
    requests,
    threshold: REQUEST_THRESHOLD,
    checked_at: new Date().toISOString(),
  };

  const response = await fetch(WEBHOOK_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Traffic-Alert-Secret": env.ALERT_WEBHOOK_SECRET,
    },
    body: JSON.stringify(payload),
  });

  const responseText = await response.text();

  if (!response.ok) {
    console.error(
      "Webhook failed:",
      response.status,
      responseText.slice(0, 500),
    );
    throw new Error("Webhook alert failed");
  }

  console.log("Webhook delivered:", response.status);
}

export default {
  async fetch() {
    return new Response("Traffic alert Worker is running.");
  },

  async scheduled(event, env, ctx) {
    ctx.waitUntil(
      (async () => {
        console.log("Scheduled run:", event.cron);

        const requests = await getRecentRequestCount(env);
        console.log("Requests in the last five minutes:", requests);

        if (requests > REQUEST_THRESHOLD) {
          console.log("Threshold exceeded; sending webhook.");
          await sendWebhookAlert(env, requests);
        } else {
          console.log("Threshold not exceeded.");
        }
      })(),
    );
  },
};

Update these three values (at the top of the file) after pasting the code:

  • ZONE_TAG: Your Cloudflare Zone ID.
  • REQUEST_THRESHOLD: The number of requests that should trigger an alert.
  • WEBHOOK_URL: Your PHP endpoint URL.

The Worker queries Cloudflare’s GraphQL endpoint using a Bearer token. The httpRequestsAdaptiveGroups dataset is the appropriate general-purpose choice here: it exposes request counts and is available as an essential dataset across Cloudflare plans.

6. Create the PHP webhook receiver

Create a PHP file on your website, such as:

1
https://example.com/private/traffic-alert.php

Store the shared secret as a server environment variable named TRAFFIC_ALERT_SECRET. The value must exactly match the value saved in the Worker’s ALERT_WEBHOOK_SECRET.

Then add this PHP code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
declare(strict_types=1);

$expectedSecret = getenv('TRAFFIC_ALERT_SECRET') ?: '';
$receivedSecret = $_SERVER['HTTP_X_TRAFFIC_ALERT_SECRET'] ?? '';

if (
    $expectedSecret === '' ||
    !is_string($receivedSecret) ||
    !hash_equals($expectedSecret, $receivedSecret)
) {
    http_response_code(401);
    exit('Unauthorized');
}

$rawBody = file_get_contents('php://input');
$payload = json_decode($rawBody, true);

if (!is_array($payload)) {
    http_response_code(400);
    exit('Invalid JSON');
}

if (($payload['event'] ?? '') !== 'traffic_threshold_exceeded') {
    http_response_code(422);
    exit('Unexpected event');
}

$requests = (int) ($payload['requests'] ?? 0);
$threshold = (int) ($payload['threshold'] ?? 0);
$checkedAt = (string) ($payload['checked_at'] ?? '');
$zone = (string) ($payload['zone'] ?? '');

error_log(
    "Traffic alert received: requests={$requests}, " .
    "threshold={$threshold}, zone={$zone}, checked_at={$checkedAt}"
);

/*
 * Add your own alert action here, for example:
 *
 * - Send an email using your application's mail service
 * - Create a record in your database
 * - Send a Slack, Discord, or Teams notification
 * - Notify an internal admin dashboard
 */

http_response_code(204);

The important part is hash_equals(): it compares the incoming shared-secret header safely before the endpoint trusts the request. A webhook URL alone is not authentication—URLs have a habit of eventually appearing somewhere they should not!

Update the comment block in the above code with your preferred alert action. For example, you could send an email, log to a database, or post to a chat service.

7. Deploy and monitor

Deploy the Worker:

1
npm run deploy

Then monitor live logs:

1
npx wrangler tail

Expected output below the threshold:

1
2
3
Scheduled run: */5 * * * *
Requests in the last five minutes: 420
Threshold not exceeded.

Expected output above the threshold:

1
2
3
4
Scheduled run: */5 * * * *
Requests in the last five minutes: 1320
Threshold exceeded; sending webhook.
Webhook delivered: 204

Cron Trigger updates can take several minutes to propagate globally, so do not panic if the first scheduled invocation is not immediate.

Troubleshooting

“Zone does not have access to the path”

Confirm that the API token has Account Analytics → Read permission and that the intended zone is included in its Zone Resources scope. Also confirm that ZONE_TAG is the Zone ID for that same Cloudflare account.

“Too many zones requested”

Keep the zone query scoped exactly as shown:

1
zones(limit: 1, filter: { zoneTag: "YOUR_ZONE_ID" })

Cloudflare applies limits to GraphQL scopes; zone-scoped queries can include up to 10 zones, but this monitor needs only one.

Too many repeated alerts

This basic version sends an alert every five minutes while traffic remains above the threshold. For production, consider adding a cooldown period—for example, one alert per hour—using Workers KV, a database, or a timestamp stored by your webhook receiver.

Conclusion

You now have a lightweight, free-plan-friendly traffic monitor that runs on Cloudflare’s network, checks recent HTTP request volume, and sends authenticated webhook alerts to your own website.

It is intentionally simple: change the threshold, replace the PHP logging action with your preferred notification method, and add cooldown logic if persistent traffic spikes would otherwise turn your inbox into a small, digital bonfire.

About BigProf Software

BigProf Software creates practical tools for building business applications faster. We are the creators of AppGini, a low-code application builder that helps developers create secure, database-driven web applications without starting every project from a blank page.