cloudflare-worker-private-google-analytics
TypeScript icon, indicating that this package has built-in type declarations

0.0.6 • Public • Published

cloudflare-worker-private-google-analytics

Middleware for proxying Google Analytics pageviews via Workers that removes all personal identifiable information

Usage

Install the package and include it in your Cloudflare Workers code. You should pass in a list of origins that will be whitelisted for sending Analytics events to your Google Analytics account.

$ yarn add cloudflare-worker-private-google-analytics
// index.js

import analytics from 'cloudflare-worker-private-google-analytics'

const analyticsResp = await analytics(event, {
  allowList: ['bytesized.xyz'],
})
if (analyticsResp) return analyticsResp

Create a KV storage GOOGLE_ANALYTICS and add the namespace to your wrangler.toml as GOOGLE_ANALYTICS.

kv-namespaces = [ 
  { binding = "GOOGLE_ANALYTICS", id = "7a557696879870789897987788798979" } 
]

In the head section of your web application, load the script helper and begin sending analytics events:

<script type="text/javascript" src="https://ga-helper.developers.workers.dev/_cf/analytics.js"></script>
<script type="text/javascript">
  const GA_ID = "$YOUR_GA_ID" // In format `UA-123456-7`
  window.ga =
    window.ga ||
    function () {
      if (!GA_ID) {
        return
      }
      ;(ga.q = ga.q || []).push(arguments)
    }
  ga.l = +new Date()
  ga('create', GA_ID, {
    'storage': 'none', // will prevent all cookies
    'anonymizeIp': true // should not be necessary anymore yet is not harmful either
  });
  ga('set', 'transport', 'beacon')
  var timeout = setTimeout(
    (onload = function () {
      clearTimeout(timeout)
      ga('send', 'pageview')
    }),
    1000,
  )
</script>

Custom script helper

The provided script helper deployed at ga-helper.developers.workers.dev is an example -- while you can use it in production, we can't promise that it won't eventually be blocked by uBlock and other similar tools.

To mitigate this, the Workers code for that domain is available in the helper directory. You can take that code and deploy it to your own workers.dev subdomain (or a custom domain) and use it accordingly.

Readme

Keywords

none

Package Sidebar

Install

npm i cloudflare-worker-private-google-analytics

Weekly Downloads

2

Version

0.0.6

License

Apache-2.0

Unpacked Size

27.3 kB

Total Files

7

Last publish

Collaborators

  • chickahoona