DEV Community

chaanli
chaanli

Posted on

Integrating Cloudflare Workers with Ad Traffic Protection: A Complete Guide

Cloudflare Workers provide an ideal edge computing platform for ad traffic filtering. Here's how to build a complete protection system.

Why Cloudflare Workers?

  • Edge processing: Filter bots before they reach your server
  • Global distribution: Low latency worldwide
  • Cost effective: $5/mo for 10M requests
  • No cold starts: Always running

Architecture

Ad Click → Cloudflare Worker → Bot Check → Clean Traffic → Landing Page
                                  ↓
                            Bot Traffic → Block/Redirect
Enter fullscreen mode Exit fullscreen mode

Worker Implementation

export default {
    async fetch(request, env) {
        const ip = request.headers.get('CF-Connecting-IP');
        const ua = request.headers.get('User-Agent');
        const ja3 = request.cf?.botManagement?.ja3Hash;

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

        // Layer 2: TLS fingerprint
        if (KNOWN_BOT_JA3.has(ja3)) {
            return redirectToDecoy(request);
        }

        // Layer 3: Behavioral check (client-side)
        const response = await fetch(request);
        const html = await response.text();
        const modified = injectBehaviorTracker(html);

        return new Response(modified, {
            headers: response.headers
        });
    }
};

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

    const score = await calculateScore(ip);
    await env.IP_CACHE.put(ip, score.toString(), {
        expirationTtl: 3600
    });
    return score;
}
Enter fullscreen mode Exit fullscreen mode

Resources

Filter at the edge. Save your server for real users.

Top comments (0)