eleventy-high-performance-blog icon indicating copy to clipboard operation
eleventy-high-performance-blog copied to clipboard

Add support for Google Analytics 4

Open nickFalcone opened this issue 2 years ago • 5 comments

Support for GA4 should be added to prevent a lapse in data collection. Universal Analytics (UA) properties will stop processing data on July 1, 2023.

cached.js contains a copy of analytics.js. I propose we add a new file, gtag.js with the contents of https://www.googletagmanager.com/gtag/js?id=my-g-id. We would need to retrieve the user's ID from a new field in metadata.json. The rationale for a second file is to separate legacy analytics.js and selectively load gtag.js if the user has a GA4 ID.

Other areas to update:

  • tests
  • README
  • Remove webvitals.js in favor of https://web.dev/vitals-ga4/

nickFalcone avatar Dec 26 '22 21:12 nickFalcone

GA4 requires much more client side JS AFAIK, so I'm not planning to add support. Legacy GA works just fine.

If you'd send a PR, I'd be happy to take a look.

cramforce avatar Dec 27 '22 00:12 cramforce

Just to say I would also be interested in understanding how to do this, even if it doesn't necessarily get merged - let me know if I can assist at all.

JamesLMilner avatar Jan 02 '23 20:01 JamesLMilner

Hi @JamesLMilner, here is what I did in my personal blog generated from the template. I see results in the ga4 dashboard so this "works" but may not be optimal given it was a self-reviewed PR over the holiday 😅. If you spot anything that could be improved, please let me know and I'll open a PR to the template.

Added a copy of gtag.js to /js and the following to _includes/layouts/base.njk:

<script async defer src="{{ "/js/gtag.js" | addHash }}"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'YOUR-G4-ID');
</script>

I also updated _data/googleanalytics.js to this:

const metadata = require('./metadata.json');

module.exports = function () {
  if (metadata.ga4Id) {
    return metadata.ga4Id;
  }
  return null;
};

and replaced the googleAnalyticsId key in _data/metadata.json with ga4Id. Lastly, I updated the line in .eleventy.js to copy ga4.js

eleventyConfig.addPassthroughCopy(GA4_ID ? 'js' : 'js/*[!ga4].*');

nickFalcone avatar Jan 16 '23 20:01 nickFalcone

You can of course totally do this!

It just won't have the 100% first-party support that was there for legacy GA

cramforce avatar Jan 16 '23 23:01 cramforce

Tomorrow UA is officially sunset.

sambacha avatar Jun 30 '23 12:06 sambacha