Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Last active September 30, 2020 20:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattlockyer/4e0ae08703954ca7b4a072887693c9c9 to your computer and use it in GitHub Desktop.
Save mattlockyer/4e0ae08703954ca7b4a072887693c9c9 to your computer and use it in GitHub Desktop.
Google Analytics for Cloudflare Workers
/********************************
* GA data
********************************/
let data = {
v: 1,
}
/********************************
* Initializes GA data
* @param {string} tid your tracking id for GA
* @param {object} req the request object from event.request
* @param {string} dp the default path you want GA to use (can override in pageview)
********************************/
export const init = (tid, { url: dl, headers }, dp) => {
const uip = headers.get('cf-connecting-ip') //calling user ip (for geo)
const ua = headers.get('user-agent')
const dr = headers.get('referer')
let cid = headers.get('cookie') //use the cloudflare cookie as a cid for ga
if (!cid) cid = `anon_${Date.now()}`
else cid = `cf_${cid.split('__cfduid=')[1]}`
data = { ...data, tid, cid, uip, ua, dr, dl, dp }
console.log('ga init', data)
}
/********************************
* Sends a page view to GA
* @param {string} dt the page title
* @param {string} dp the path
* @returns a promise (should be waited on by caller)
********************************/
export const pageview = async (dt, dp = data.dp) => {
await send({ ...data, t: 'pageview', dt, dp, })
}
/********************************
* Sends an event to GA
* @param {string} ec event category
* @param {string} ea event action
* @param {string} el event label
* @param {number} ev event value
* @returns a promise (should be waited on by caller)
********************************/
export const event = async (ec, ea, el = "", ev = 0) => {
await send({ ...data, t: 'event', ec, ea, el, ev, })
}
/********************************
* Sends the data to GA
* @returns a promise
********************************/
const send = async (data) => {
const uri = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&')
await fetch('http://www.google-analytics.com/collect?' + uri)
}
@NimaBenisi
Copy link

Hi there,
How can I use it? Could you please guide me?
I'm getting this error 'We could not find that Worker script on your account. (Code: 10007)' and 'Uncaught SyntaxError: Unexpected token 'export' at line 13 (Code: 10021)'

Thanks

@mattlockyer
Copy link
Author

mattlockyer commented Jun 7, 2020

You need to use wrangler from cloudflare and in your wrangler.toml set type = webpack because it's a module.
Save this gist as it's own JS file, in my case util/ga.js
Then in your request handler file, use it something like this:

import { init as initGA, pageview, event } from './util/ga'
addEventListener('fetch', (e) => {
	e.respondWith(handleRequest(e.request, e))
})
async function handleRequest(req, e) {
	const path = req.url.split('.com')[1] //or whatever your tld is
	//GA
	initGA(UA-XXXXXXXXXXX-X, req, path)
	await pageview(`hello from my cloudflare worker`)
...
}

Fill in your UA-XXXXXXXXXXX-X

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment