Created
November 29, 2018 07:45
-
-
Save dustinrecko/ede7db9f6fcc1316394dc5c92b978c89 to your computer and use it in GitHub Desktop.
Cloudflare Worker Googlebot Tracking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const analyticsId = 'UA-xxxxxxxxx-x' | |
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event)) | |
}) | |
/** | |
* Check request object for Googlebot UA to send tracking data | |
* @param {Event} event | |
*/ | |
async function handleRequest(event) { | |
const request = event.request | |
const ua = request.headers.get('user-agent') | |
let botName; | |
// If Googlebot then track hit in Analytics | |
if ((botName = ua.match(/[^\s]+\-Google[^\s;]*|Googlebot[^\s;]*/g))) { | |
const response = await fetch(request) | |
event.waitUntil(analyticsHit( | |
{ | |
uip: request.headers.get('CF-Connecting-IP'), | |
dl: request.url, | |
cd1: response.status, | |
cd2: botName[0], | |
cd3: request.method, | |
cd4: Math.round(+new Date() / 1000.0) | |
} | |
)) | |
return response | |
} | |
// or just return the original content | |
return fetch(request) | |
} | |
/** | |
* Send bot tracking data using Analytics Measurement Protocol | |
* @param {Object} tracking | |
*/ | |
function analyticsHit(tracking) { | |
let payload = '?v=1&t=pageview&tid='+analyticsId | |
for(var key in tracking) { | |
payload += '&'+key+'='+tracking[key] | |
} | |
payload += '&cid='+[Math.round(Math.random() * 2147483647),Math.round(+new Date() / 1000.0)].join('.') | |
return fetch(encodeURI('https://www.google-analytics.com/collect'+payload)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment