Skip to content

Instantly share code, notes, and snippets.

@dustinrecko
Created November 29, 2018 07:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinrecko/ede7db9f6fcc1316394dc5c92b978c89 to your computer and use it in GitHub Desktop.
Save dustinrecko/ede7db9f6fcc1316394dc5c92b978c89 to your computer and use it in GitHub Desktop.
Cloudflare Worker Googlebot Tracking
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