Analytics and cookie consent
Guides
2 min read
How to add an analytics script, with or without the cookie consent banner.
Nightgrid ships with no analytics, no tracking scripts and no third-party cookies. The consent banner collects a choice and does nothing else until you connect something to it.
There are two ways to add analytics. Which one you need depends on the tool and on the law that applies to you. This page is not legal advice: check your tool’s own guidance and, when in doubt, ask someone qualified.
Option 1: a script that loads for everyone
Some analytics tools are built to work without cookies. Their makers say what that means for consent; read it before you rely on it.
- Copy the current snippet from your provider’s dashboard. Do not copy one from an old tutorial: these snippets change.
- Paste it into the
<head>ofsrc/layouts/BaseLayout.astro. - If nothing on your site needs consent any more, switch the banner off in
src/data/consent.ts:
export const consent: Consent = {
enabled: false, // removes the banner and the footer button
// ...
};Option 2: a script that waits for consent
For a tool that sets cookies or follows visitors, load it only after the visitor accepts.
What the banner gives you
document.documentElement.dataset.consentis'accepted'or'declined'once a choice exists, and unset before that.- The choice is kept in
localStorageundercookie-consent:<id>, not in a cookie. - A
consent-changeevent is sent ondocumentwithdetail.choice, when the visitor chooses and again on each page load while a choice exists.
The pattern
Add this before </head> in src/layouts/BaseLayout.astro, and put your provider’s own loading code inside loadAnalytics:
<script is:inline>
let analyticsLoaded = false;
function loadAnalytics() {
if (analyticsLoaded) return;
analyticsLoaded = true;
// Your provider's snippet goes here, copied from its dashboard.
}
if (document.documentElement.dataset.consent === 'accepted') loadAnalytics();
document.addEventListener('consent-change', (event) => {
if (event.detail?.choice === 'accepted') loadAnalytics();
});
</script>A visitor who later declines keeps the script for the rest of that page view; it is not loaded on the next page. If your provider has its own switch for withdrawing consent, call it when detail.choice is 'declined'.
Tip
To ask every visitor again, for example after changing your privacy policy, change
idinsrc/data/consent.ts. Earlier choices are stored under the old id and no longer count.
Remember to name the tool, and what it collects, on your privacy page.