Google Analytics and the cookie banner
Every site comes with visitor analytics that work without cookies and need no cookie banner. That is enough for most people.
Sometimes Google Analytics is needed anyway: for conversion tracking on ads, for online shop reporting, or because your marketing partner works with it. Those are perfectly valid reasons, and you can add it to your site. This page explains what that takes in practice.
Three things have to happen
Adding Google Analytics is not just pasting in a tracking snippet. Your site is protected by a security policy that blocks outside scripts from loading, so the snippet on its own does nothing. It shows no error, it simply stays silent.
The steps are:
- Allow Google's addresses in the site's security policy.
- Add Google's tracking code to the page template.
- Add a cookie banner that asks for consent before tracking starts.
The third step is not optional. Google Analytics sets cookies, and setting cookies requires the visitor's consent. That is why the banner appears: the requirement comes from the tracking cookies, not from us.
The easy way: ask the AI assistant
Your site's source code is yours, so the AI assistant can make these changes for you. Tell it something like:
Add Google Analytics to the site, measurement id G-XXXXXXXXXX. Allow Google's addresses in the security policy and add a cookie banner that asks for consent before tracking starts.
If something goes wrong, you can always ask the assistant to undo the changes.
If you do it yourself
The site's security policy is built in astro.config.mjs. Google's addresses go in the scriptDirective setting:
experimental: {
csp: {
scriptDirective: {
resources: [
"'self'",
'https://www.googletagmanager.com',
'https://www.google-analytics.com',
],
},
},
},
Note 'self' first in the list. The setting replaces the defaults entirely rather than adding to them, so if you leave it out, your site's own scripts stop working.
After that you add Google's tracking code to the page template, and a cookie banner that starts the tracking only once consent is given.
Worth knowing beforehand
The banner shows for everyone. It is the first thing a visitor meets on your site, and some leave because of it. That is the price of Google Analytics.
The security policy loosens. Allowing outside scripts opens a route into your site that did not exist before. Allow only the addresses you actually need.
Visitor data goes to Google. That is the whole point of the tool, but it is worth saying out loud: this is a US advertising company, and you have to mention it in your privacy policy.
Your own analytics keep running. They do not switch off, so you see the numbers from both. They will never match, because Google Analytics only sees the visitors who accept cookies.
Need help?
If you would rather not do this yourself, get in touch. We are happy to help.