← Back

Send Visit Events From Your Cloudflare Website (Using a Worker)

Are You on an Enterprise Cloudflare Plan?
If so, use the Cloudflare Logpush integration to connect your website instead.

Before You Start

If your website is not already connected to Cloudflare:

Make sure that the DNS records for each website hostname you want to track, such as example.com and www.example.com, have Proxied (orange cloud) enabled.

Step 1: Create a Worker

const KNOWN_AGENTS_ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"

const REQUEST_HEADER_NAMES = [
    "cf-connecting-ip",
    "user-agent",
    "host",
    "x-forwarded-host",
    "referer",
    "signature",
    "signature-agent",
    "signature-input",
]

const RESPONSE_HEADER_NAMES = [
    "content-type",
]

export default {
    async fetch(request, env, ctx) {
        const startTime = Date.now()
        const response = await fetch(request)
        const duration = Date.now() - startTime
        ctx.waitUntil(trackVisit(request, response, duration).catch(() => {}))
        return response
    },
}

async function trackVisit(request, response, duration) {
    const requestURL = new URL(request.url)
    await fetch("https://api.knownagents.com/visits", {
        method: "POST",
        headers: {
            "Authorization": `Bearer ${KNOWN_AGENTS_ACCESS_TOKEN}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            request_path: requestURL.pathname + requestURL.search,
            request_method: request.method,
            response_status_code: response.status,
            response_headers: Object.fromEntries(
                [...response.headers].filter(([headerName]) => {
                    return RESPONSE_HEADER_NAMES.includes(headerName)
                })
            ),
            response_duration_in_milliseconds: duration,
            request_headers: Object.fromEntries(
                [...request.headers].filter(([headerName]) => {
                    return REQUEST_HEADER_NAMES.includes(headerName)
                })
            ),
        }),
    })
}

Tips

Step 2: Test Your Integration

If your website is correctly connected, you should see visits from a test agent in the realtime timeline within a few seconds.