Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Google Analytics 4 #160

Open
nickFalcone opened this issue Dec 26, 2022 · 5 comments
Open

Add support for Google Analytics 4 #160

nickFalcone opened this issue Dec 26, 2022 · 5 comments

Comments

@nickFalcone
Copy link
Contributor

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:

@cramforce
Copy link
Collaborator

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.

@JamesLMilner
Copy link

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.

@nickFalcone
Copy link
Contributor Author

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].*');

@cramforce
Copy link
Collaborator

You can of course totally do this!

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

@sambacha
Copy link

Tomorrow UA is officially sunset.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants