DEV Community

chaanli
chaanli

Posted on

Building Ad Traffic Protection with Cloudflare Workers: Edge-Level Bot Detection

Cloudflare Workers run at the edge — closer to users than your origin server. This makes them perfect for first-pass bot detection.

Why Edge Detection Matters

By the time bot traffic reaches your server, you've already paid for the bandwidth and compute. Edge detection blocks bots before they cost you.

Implementation

export default {
    async fetch(request, env) {
        const clientIP = request.headers.get('CF-Connecting-IP');
        const country = request.headers.get('CF-IPCountry');
        const ja3 = request.cf?.tlsClientAuth?.ja3Hash || '';

        // Layer 1: IP reputation check
        const ipScore = await checkIPReputation(env, clientIP);
        if (ipScore < 20) {
            return new Response('Access denied', { status: 403 });
        }

        // Layer 2: TLS fingerprint
        if (KNOWN_BOT_JA3.includes(ja3)) {
            return new Response('Access denied', { status: 403 });
        }

        // Layer 3: Geo consistency
        const tzHeader = request.headers.get('X-Timezone');
        if (!isGeoConsistent(country, tzHeader)) {
            // Flag for behavioral analysis
            request.headers.set('X-Suspicious', 'geo-mismatch');
        }

        // Pass to origin with risk score
        const modifiedRequest = new Request(request);
        modifiedRequest.headers.set('X-Risk-Score', ipScore.toString());
        return fetch(modifiedRequest);
    }
};

async function checkIPReputation(env, ip) {
    const cached = await env.IP_CACHE.get(ip);
    if (cached) return parseInt(cached);

    // Check against proprietary threat intelligence
    const score = await queryReputationAPI(ip);
    await env.IP_CACHE.put(ip, score.toString(), { expirationTtl: 3600 });
    return score;
}
Enter fullscreen mode Exit fullscreen mode

Benefits

  • < 1ms latency added to requests
  • Global distribution — runs in 300+ locations
  • Free tier supports 100K requests/day

Full Stack

Move your first line of defense to the edge.

Top comments (0)