Keep TermsFeed Free Cookie Consent working when your app changes routes without a page load
Load Cookie Consent once in the host page of your single-page application, and drive page views and route code from the consent state. A single-page application (SPA) changes routes without loading a new page, so a route change never restarts Cookie Consent, which reads tagged scripts only when it starts.
Every example starts from the code the TermsFeed generator writes. Create it with Install a Cookie Banner on Any Website.
Step 1: Put the loader, the configuration, and the tagged scripts in the host page
Paste the Cookie Consent block and every tagged script into the HTML page that loads your app, outside the element your framework mounts into. Replace the measurement ID of the tagged Google Analytics 4 script and the options in this Vite index.html with your own.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Example App</title>
<script type="text/plain" data-cookie-consent="tracking" async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script type="text/plain" data-cookie-consent="tracking">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
<!-- Cookie Consent by TermsFeed https://www.TermsFeed.com -->
<script type="text/javascript" src="https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js" charset="UTF-8"></script>
<script type="text/javascript" charset="UTF-8">
document.addEventListener('DOMContentLoaded', function () {
cookieconsent.run({"notice_banner_type":"headline","consent_type":"express","palette":"dark","language":"en","page_load_consent_levels":["strictly-necessary"],"website_name":"Example App"});
});
</script>
<noscript>Free cookie consent management tool by <a href="https://www.termsfeed.com/">TermsFeed Generator</a></noscript>
<!-- End Cookie Consent by TermsFeed https://www.TermsFeed.com -->
<!-- Below is the link that users can use to open Preferences Center to change their preferences. Do not modify the ID parameter. Place it where appropriate, style it as needed. -->
<a href="#" id="open_preferences_center">Update cookies preferences</a>
</body>
</html>
Write every tagged script as a plain <script> element, never with a component that recreates script elements, such as next/script.
Under a Content Security Policy, write the same nonce on the loader tag, the inline run() script, and each tagged script. Find where your framework puts the nonce in Content Security Policy.
Step 2: Load the Cookie Consent loader and call run() once per page load
Call cookieconsent.run() once, from the host page, never from a component that mounts again on each route or from a route event. A second run() call keeps the first instance and returns the first object. The options of the second call are ignored, including a new language. Visitors pick the language in the Preferences Center menu for the current page.
The generator wraps run() in a DOMContentLoaded listener, so a script that starts after that event, such as a Next.js afterInteractive script, never calls run(), and no consent banner appears. Start such a script with this check.
function startCookieConsent() {
window.cookieconsent.run({
notice_banner_type: 'headline',
consent_type: 'express',
palette: 'dark',
language: 'en',
page_load_consent_levels: ['strictly-necessary'],
website_name: 'Example Site'
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startCookieConsent);
} else {
startCookieConsent();
}
Step 3: Send page views on route changes from the consent state
Send a page view from your router only when the visitor accepted tracking, by reading cookieconsent.cookieConsentObject.userConsent. The tagged Google Analytics 4 script runs once, when the visitor accepts or on page load, and sends the first page view itself.
Google Analytics 4 sends a page view on each browser history change by itself, through the Enhanced measurement option "Page changes based on browser history events". Keep either that option or your router hook, so each route counts once. Turn the option off in your web data stream, as the Google Analytics help describes.
HubSpot records only the page it loaded on, so the function pushes setPath and trackPageView to _hsq on each later route. Call it from the route change hook of your router, named in the code comments or in the section of your framework. The function skips its first call, because each hook runs on the first page too, where the tagged script and the HubSpot code count the page themselves.
var firstRouteSeen = false;
function sendPageViewAfterConsent() {
if (!firstRouteSeen) {
firstRouteSeen = true;
return;
}
var cc = window.cookieconsent && window.cookieconsent.cookieConsentObject;
if (!cc || cc.userConsent.acceptedLevels.tracking !== true) {
return;
}
if (typeof gtag === 'function') {
gtag('event', 'page_view', {
page_location: location.href,
page_title: document.title
});
}
if (window._hsq) {
window._hsq.push(['setPath', location.pathname + location.search]);
window._hsq.push(['trackPageView']);
}
}
// React Router: useEffect(sendPageViewAfterConsent, [location.pathname]);
// Vue Router: router.afterEach(function () { sendPageViewAfterConsent(); });
// Angular: router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe(sendPageViewAfterConsent);
// SvelteKit: afterNavigate(sendPageViewAfterConsent);
Step 4: Load code that a route adds later from the consent state
Load a script that a route adds, such as a map, a chat widget, or a video player, with this function. It loads the script for a released category, now or as soon as Cookie Consent releases it. Before an answer, acceptedLevels holds the categories released on page load, so in implied mode or with page_load_consent_levels the function loads their scripts at once. Copy cookieConsentAccepted() too, from Read the consent state in the browser with cookieConsentObject.
function loadWhenAccepted(category, src) {
function inject() {
if (document.querySelector('script[src="' + src + '"]')) {
return;
}
var script = document.createElement('script');
script.src = src;
script.async = true;
document.head.appendChild(script);
}
var cc = window.cookieconsent && window.cookieconsent.cookieConsentObject;
var releasedOnPageLoad = cc && cc.userConsent.userAccepted !== true && cc.userConsent.acceptedLevels[category] === true;
if (cookieConsentAccepted(category) || releasedOnPageLoad) {
inject();
return;
}
// 'page_load' reaches a listener added before run() with the page-load release, 'choice' each answer
document.addEventListener('cc_userConsentSaved', function listener(event) {
if (event.details[category] === true) {
document.removeEventListener('cc_userConsentSaved', listener);
inject();
}
});
}
// Example: a chat widget on the support route
loadWhenAccepted('functionality', 'https://widget.example.com/chat.js');
Pass only categories listed in your notice_banner_purposes_levels, because older cookies keep true for a category you have since removed.
Grant vendor signals from scripts_specific_loaded with callbacks_force: true, and Google Consent Mode signals from user_consent_saved with user_consent_saved_on_page_load: true. Map each category with Map Categories to Vendor Consent Signals.
Step 5: Open the Preferences Center from your app
Give your "Cookie settings" link the id open_preferences_center, or a class you pass in open_preferences_center_selector. Cookie Consent checks the selector on every click, so links your framework renders after run() open the Preferences Center too. Cookie Consent cancels the default action of the click, so href="#" changes nothing, and a router link that checks event.defaultPrevented stays on the route.
A button that calls cookieconsent.openPreferencesCenter() works once Cookie Consent has started. Calling it earlier throws TypeError, so call window.cookieconsent?.cookieConsentObject?.openPreferencesCenter(), or keep the selector. Set up the link with Add a Cookie Settings Link.
Step 6: Keep the consent banner when your framework replaces the body
Turbo Drive and the Astro router swap the whole <body> on navigation, which removes the consent banner and the Preferences Center. The Preferences Center comes back on its next opening, but the consent banner does not, and run() does not start a second instance.
Move the consent banner into the incoming body with the astro:before-swap script of the Astro layout or the turbo:before-render script of the Turbo layout, placed after the Cookie Consent block. A site that sets notice_banner_append to beforeend uses append instead of prepend in those scripts.
Declare the cookieconsent global for TypeScript
Declare window.cookieconsent in a .d.ts file, so TypeScript accepts calls to the global without any.
// types/cookieconsent.d.ts
type CookieConsentCategory = 'strictly-necessary' | 'functionality' | 'tracking' | 'targeting';
interface CookieConsentObject {
userConsent: {
acceptedLevels: Record<CookieConsentCategory, boolean>;
userAccepted: boolean;
};
userConsentToken?: string;
openPreferencesCenter(): void;
isLevelInPurposes(level: CookieConsentCategory): boolean;
}
interface CookieConsentGlobal {
run(options: Record<string, unknown>): CookieConsentObject | undefined;
openPreferencesCenter?: () => void;
cookieConsentObject?: CookieConsentObject;
}
declare global {
interface Window {
cookieconsent?: CookieConsentGlobal;
_hsq?: unknown[][];
}
function gtag(...args: unknown[]): void;
}
export {};
React: Paste the Cookie Consent code into index.html
Use the index.html of Step 1 with <div id="root"></div> and /src/main.jsx. Create React App keeps index.html in public/, with no module script line.
This button opens the Preferences Center.
export function CookieSettingsButton() {
return (
<button
type="button"
onClick={() => window.cookieconsent?.cookieConsentObject?.openPreferencesCenter()}
>
Cookie settings
</button>
);
}
Next.js: Load Cookie Consent with next/script from the root layout
Load the Cookie Consent loader with next/script and strategy="beforeInteractive", and call run() from a second script with strategy="afterInteractive". The Next.js documentation names cookie consent managers as a use for beforeInteractive, which runs once per document load.
Both routers share this module.
// lib/cookie-consent.ts
export const cookieConsentRunScript = `
function startCookieConsent() {
window.cookieconsent.run({
notice_banner_type: 'headline',
consent_type: 'express',
palette: 'dark',
language: 'en',
page_load_consent_levels: ['strictly-necessary'],
website_name: 'Example Site'
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startCookieConsent);
} else {
startCookieConsent();
}
`;
export const ga4ConfigScript = `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
`;
Leave async off the external tagged script, because React moves a script with src and async into the head and de-duplicates it.
Load Cookie Consent in the Next.js App Router from app/layout.tsx
// app/layout.tsx
import Script from 'next/script';
import type { ReactNode } from 'react';
import { cookieConsentRunScript, ga4ConfigScript } from '@/lib/cookie-consent';
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<head>
<script
type="text/plain"
data-cookie-consent="tracking"
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
/>
<script
type="text/plain"
data-cookie-consent="tracking"
dangerouslySetInnerHTML={{ __html: ga4ConfigScript }}
/>
</head>
<body>
{children}
<footer>
<a href="#" id="open_preferences_center">Update cookies preferences</a>
</footer>
<Script
src="https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"
strategy="beforeInteractive"
/>
<Script id="cookie-consent-run" strategy="afterInteractive">
{cookieConsentRunScript}
</Script>
<noscript>
Free cookie consent management tool by <a href="https://www.termsfeed.com/">TermsFeed Generator</a>
</noscript>
</body>
</html>
);
}
Load Cookie Consent in the Next.js Pages Router from _document.tsx and _app.tsx
Put the loader and the tagged scripts in pages/_document.tsx. The Pages Router accepts a beforeInteractive script only inside _document.
// pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';
import { ga4ConfigScript } from '@/lib/cookie-consent';
export default function Document() {
return (
<Html lang="en">
<Head>
<script
type="text/plain"
data-cookie-consent="tracking"
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
/>
<script
type="text/plain"
data-cookie-consent="tracking"
dangerouslySetInnerHTML={{ __html: ga4ConfigScript }}
/>
</Head>
<body>
<Main />
<NextScript />
<Script
src="https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"
strategy="beforeInteractive"
/>
</body>
</Html>
);
}
Call run() from pages/_app.tsx.
// pages/_app.tsx
import type { AppProps } from 'next/app';
import Script from 'next/script';
import { cookieConsentRunScript } from '@/lib/cookie-consent';
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} />
<Script id="cookie-consent-run" strategy="afterInteractive">
{cookieConsentRunScript}
</Script>
</>
);
}
Next.js route changes: page views
Export the Step 3 function from a module, and call it from a client component rendered once in the root layout, in a useEffect on usePathname(). The Pages Router exposes the same moment as the routeChangeComplete event of useRouter().events, which skips the first page, so call the function once on mount too.
Next.js with Google Consent Mode v2 and next/third-parties
Load the Google tag untagged with GoogleAnalytics from @next/third-parties/google, set every consent signal to denied before it, and send the signals from user_consent_saved. The component loads gtag.js after hydration and does not accept a type="text/plain" attribute, so Cookie Consent never holds it.
The Consent Mode defaults must be the first script in <head>, after only the charset meta, above the Google tag, any Google Tag Manager container, and the Cookie Consent block. Put them in a beforeInteractive inline script above the loader. The Next.js documentation states that beforeInteractive scripts always go into the <head>, wherever the layout places them, and run in the order they are placed.
// lib/consent-mode.ts
export const consentModeDefaults = `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('consent', 'default', {
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied',
analytics_storage: 'denied',
functionality_storage: 'denied',
personalization_storage: 'denied',
wait_for_update: 500
});
`;
export const cookieConsentRunScript = `
function startCookieConsent() {
window.cookieconsent.run({
notice_banner_type: 'headline',
consent_type: 'express',
palette: 'dark',
language: 'en',
page_load_consent_levels: ['strictly-necessary'],
website_name: 'Example Site',
user_consent_saved_on_page_load: true,
callbacks: {
user_consent_saved: function (details) {
gtag('consent', 'update', {
analytics_storage: details.tracking ? 'granted' : 'denied',
ad_storage: details.targeting ? 'granted' : 'denied',
ad_user_data: details.targeting ? 'granted' : 'denied',
ad_personalization: details.targeting ? 'granted' : 'denied',
functionality_storage: details.functionality ? 'granted' : 'denied',
personalization_storage: details.functionality ? 'granted' : 'denied'
});
}
}
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startCookieConsent);
} else {
startCookieConsent();
}
`;
In this layout, the run() script and the Google tag both load after hydration, in either order, and the update usually reaches the Google tag within its wait_for_update time.
// app/layout.tsx
import Script from 'next/script';
import { GoogleAnalytics } from '@next/third-parties/google';
import type { ReactNode } from 'react';
import { consentModeDefaults, cookieConsentRunScript } from '@/lib/consent-mode';
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Script id="consent-mode-default" strategy="beforeInteractive">
{consentModeDefaults}
</Script>
<Script
src="https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"
strategy="beforeInteractive"
/>
<Script id="cookie-consent-run" strategy="afterInteractive">
{cookieConsentRunScript}
</Script>
</body>
<GoogleAnalytics gaId="G-XXXXXXXXXX" />
</html>
);
}
A decline sends denied for every optional category, and a withdrawal sends denied as soon as the visitor saves it. Set up the full flow with Google Consent Mode v2.
Vue and Nuxt: Put the Cookie Consent code in index.html or nuxt.config.ts
Keep every tagged script out of .vue files, because the Vue template compiler ignores <script> tags inside component templates.
Nuxt 3 and 4: Declare the scripts in nuxt.config.ts
Declare the tagged scripts, the loader, and the run() call in the app.head option of nuxt.config.ts, never with useHead in a page. The tagPosition: 'bodyClose' key places an entry before </body>.
// nuxt.config.ts
export default defineNuxtConfig({
app: {
head: {
script: [
{
type: 'text/plain',
'data-cookie-consent': 'tracking',
async: true,
src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX',
},
{
type: 'text/plain',
'data-cookie-consent': 'tracking',
innerHTML:
"window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-XXXXXXXXXX');",
},
{
src: 'https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js',
tagPosition: 'bodyClose',
},
{
tagPosition: 'bodyClose',
innerHTML: `
function startCookieConsent() {
window.cookieconsent.run({
notice_banner_type: 'headline',
consent_type: 'express',
palette: 'dark',
language: 'en',
page_load_consent_levels: ['strictly-necessary'],
website_name: 'Example Site'
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startCookieConsent);
} else {
startCookieConsent();
}
`,
},
],
noscript: [
{
tagPosition: 'bodyClose',
innerHTML:
'Free cookie consent management tool by <a href="https://www.termsfeed.com/">TermsFeed Generator</a>',
},
],
},
},
});
Leave charset out of the script entries. The Nuxt head manager keeps only one tag with a charset key, the page character set, so the loader and the run() script never reach the HTML.
Vue and Nuxt route changes: page views
Call the Step 3 function from router.afterEach, on the router you create in src/router/index.js in a Vue app. In Nuxt, call it from useRouter().afterEach in a plugin whose file name ends in .client.ts, which keeps it out of server rendering, where window does not exist.
Load Nuxt Scripts when the visitor accepts a category
Pass a consent trigger from useScriptTriggerConsent() to a Nuxt Scripts script, and grant it from scripts_specific_loaded. Nuxt Scripts loads a script with that trigger only once its consent value resolves to true. Create that value as a promise in an app.head entry before the Cookie Consent block.
// nuxt.config.ts (a new promise entry and a changed run() entry)
export default defineNuxtConfig({
app: {
head: {
script: [
{
innerHTML:
'window.cookieConsentTracking = new Promise(function (resolve) { window.cookieConsentGrantTracking = resolve; });',
},
// ...the loader entry from "Nuxt 3 and 4: Declare the scripts in nuxt.config.ts"
{
tagPosition: 'bodyClose',
innerHTML: `
function startCookieConsent() {
window.cookieconsent.run({
notice_banner_type: 'headline',
consent_type: 'express',
palette: 'dark',
language: 'en',
page_load_consent_levels: ['strictly-necessary'],
website_name: 'Example Site',
callbacks_force: true,
callbacks: {
scripts_specific_loaded: function (level) {
switch (level) {
case 'tracking':
window.cookieConsentGrantTracking(true);
break;
}
}
}
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startCookieConsent);
} else {
startCookieConsent();
}
`,
},
],
},
},
});
Pass the promise to the trigger in app.vue.
<!-- app.vue -->
<script setup lang="ts">
const trigger = useScriptTriggerConsent({
consent: import.meta.client ? (window as any).cookieConsentTracking : false,
});
useScriptGoogleAnalytics({
id: 'G-XXXXXXXXXX',
scriptOptions: { trigger },
});
</script>
<template>
<NuxtPage />
</template>
Leave Google Analytics out of the tagged app.head entries when Nuxt Scripts loads it, so the page carries one Google tag. Nuxt Scripts does not unload a script after a withdrawal, and from the next page load, scripts_specific_loaded no longer runs for tracking, so the promise never resolves.
Read consent on the Nuxt server with useCookie
Read the cookie_consent_level cookie with useCookie to decide on the server what a page renders.
// composables/useTrackingConsent.ts
export function useTrackingConsent() {
const levels = useCookie<Record<string, boolean> | null>('cookie_consent_level', { readonly: true });
const answered = useCookie<boolean | null>('cookie_consent_user_accepted', { readonly: true });
return computed(() => answered.value === true && levels.value?.tracking === true);
}
The cookie_consent_level cookie exists before the visitor answers and holds the categories released on page load, so the composable checks cookie_consent_user_accepted too.
Angular: Paste the Cookie Consent code into src/index.html and wrap the cookieconsent global in a service
Angular strips <script> tags from component templates, so a tagged script never goes into a component. Load the loader with its own tag in index.html, never through the scripts array of angular.json. Under a Content Security Policy, write the nonce on each Cookie Consent tag and on <app-root> as ngCspNonce, which covers only the styles Angular adds itself.
Wrap the cookieconsent global in an Angular service
This service reads the consent state, opens the Preferences Center, and sends page views with the Step 3 function, exported from src/app/page-views.ts. It checks the platform first, so server rendering with @angular/ssr never reaches window.
// src/app/cookie-consent.service.ts
import { DestroyRef, Injectable, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
import { sendPageViewAfterConsent } from './page-views';
type CookieConsentCategory = 'strictly-necessary' | 'functionality' | 'tracking' | 'targeting';
interface CookieConsentObject {
userConsent: {
acceptedLevels: Record<CookieConsentCategory, boolean>;
userAccepted: boolean;
};
openPreferencesCenter(): void;
}
declare global {
interface Window {
cookieconsent?: { cookieConsentObject?: CookieConsentObject };
_hsq?: unknown[][];
}
function gtag(...args: unknown[]): void;
}
@Injectable({ providedIn: 'root' })
export class CookieConsentService {
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
hasConsent(category: CookieConsentCategory): boolean {
if (!this.isBrowser) return false;
return window.cookieconsent?.cookieConsentObject?.userConsent.acceptedLevels[category] === true;
}
openPreferences(): void {
if (!this.isBrowser) return;
window.cookieconsent?.cookieConsentObject?.openPreferencesCenter();
}
trackPageViews(): void {
if (!this.isBrowser) return;
this.router.events
.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
takeUntilDestroyed(this.destroyRef),
)
.subscribe(() => sendPageViewAfterConsent());
}
}
Start the page views once, from the root component.
// src/app/app.component.ts
import { Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CookieConsentService } from './cookie-consent.service';
import { SiteFooterComponent } from './site-footer.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, SiteFooterComponent],
template: `<router-outlet /><app-site-footer />`,
})
export class AppComponent {
constructor() {
inject(CookieConsentService).trackPageViews();
}
}
The footer link carries the id open_preferences_center.
// src/app/site-footer.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-site-footer',
standalone: true,
template: `
<footer>
<a href="#" id="open_preferences_center">Update cookies preferences</a>
</footer>
`,
})
export class SiteFooterComponent {}
SvelteKit: Paste the Cookie Consent code into src/app.html
Paste the Cookie Consent block after the element that holds %sveltekit.body%. The SvelteKit documentation asks for %sveltekit.body% inside a <div>, and hydration touches only that <div>.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- The tagged scripts of Step 1 -->
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
<!-- The Cookie Consent block and the open_preferences_center link of Step 1 -->
</body>
</html>
Add nonce="%sveltekit.nonce%" to each tag when kit.csp runs in nonce mode. SvelteKit fills the placeholder for scripts you include by hand. Keep tagged scripts out of <svelte:head>.
Call the Step 3 function from afterNavigate in src/routes/+layout.svelte.
Astro: Keep the code in the layout head and move the consent banner on each swap
Place the tagged scripts and the Cookie Consent block in the <head> of the layout every page uses, each with is:inline. The is:inline directive makes Astro write a script exactly as you wrote it instead of bundling it. With the router, Astro leaves a head script in place when the new page carries the same script.
---
// src/layouts/BaseLayout.astro
import { ClientRouter } from 'astro:transitions';
const { title } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
<ClientRouter />
<script is:inline type="text/plain" data-cookie-consent="tracking" async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script is:inline type="text/plain" data-cookie-consent="tracking">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
<script is:inline src="https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js" charset="UTF-8"></script>
<script is:inline charset="UTF-8">
document.addEventListener('DOMContentLoaded', function () {
cookieconsent.run({"notice_banner_type":"headline","consent_type":"express","palette":"dark","language":"en","page_load_consent_levels":["strictly-necessary"],"website_name":"Example Site"});
});
</script>
<script is:inline>
document.addEventListener('astro:before-swap', function (event) {
var styles = document.head.querySelectorAll('style');
for (var i = 0; i < styles.length; i++) {
if (styles[i].textContent.indexOf('termsfeed-com---') !== -1) {
event.newDocument.head.append(styles[i]);
}
}
var banner = document.getElementById('termsfeed-com---nb');
if (!banner) return;
var node = banner.closest('.termsfeed-com---nb-interstitial-overlay') || banner;
event.newDocument.body.prepend(node);
});
</script>
</head>
<body>
<slot />
<footer>
<a href="#" id="open_preferences_center">Update cookies preferences</a>
</footer>
<noscript>Free cookie consent management tool by <a href="https://www.termsfeed.com/">TermsFeed Generator</a></noscript>
</body>
</html>
Astro 5 and later name the router <ClientRouter />. Astro 3 and 4 name it <ViewTransitions />, imported from the same module.
The last script of the layout moves the Cookie Consent <style> element into the incoming <head> too. Without the lines that move the <style> element, the consent banner and the Preferences Center show without their styles after the first navigation.
Call the Step 3 function from astro:page-load, which fires on the first page and after every navigation.
Turbo Drive in Rails and Hotwire: Load the code in the head and move the consent banner on each render
Put the tagged scripts and the Cookie Consent block in the <head> of app/views/layouts/application.html.erb. The Turbo handbook states that Turbo Drive adds only the head scripts the current page does not already hold, and evaluates body scripts each time it renders a page.
Add nonce="<%= content_security_policy_nonce %>" to each tag when the app sends a Content Security Policy.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example App</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<!-- The tagged scripts, then the loader and run() script of Step 1 -->
<script>
document.addEventListener('turbo:before-render', function (event) {
var banner = document.getElementById('termsfeed-com---nb');
if (!banner) return;
var node = banner.closest('.termsfeed-com---nb-interstitial-overlay') || banner;
var cachedCopy = event.detail.newBody.querySelector('#termsfeed-com---nb');
if (cachedCopy) {
(cachedCopy.closest('.termsfeed-com---nb-interstitial-overlay') || cachedCopy).remove();
}
event.detail.newBody.prepend(node);
});
</script>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<%= yield %>
<footer>
<a href="#" id="open_preferences_center">Update cookies preferences</a>
</footer>
<noscript>Free cookie consent management tool by <a href="https://www.termsfeed.com/">TermsFeed Generator</a></noscript>
</body>
</html>
Keep the inline run() script identical on every page, because Turbo evaluates a head script whose content differs from the current one.
The data-turbo-permanent attribute does not keep the consent banner in the page. Turbo keeps a permanent element only when the new page holds an element with the same id, and the consent banner exists only in the browser.
Call the Step 3 function from turbo:load, which fires on the first page and after every Turbo visit.
How to verify Cookie Consent in your single-page app
Close every private window, then test a production build in a new one, with express consent, the generator page_load_consent_levels, and debug: true in the run() options. Build with npm run build, and serve the output with npm run preview (Vite, Nuxt, SvelteKit, and Astro) or npm start (Next.js). Serve a Create React App build with npx serve -s build, a Rails app with bin/rails server -e production, and an Angular ng build through your own server. Rebuild and serve the app again after each change.
- Open Chrome DevTools, select the Network tab, type
cookie-consentin the filter box, and load your app. The loadercookie-consent.js, the scriptcookie-consent-code.js, and the ping towww.termsfeed.comappear, and the consent banner shows. - Open the Console. No line contains
violates the following Content Security Policy directive. - Return to the Network tab, change the filter to
collect, and follow 2 links in your app. The consent banner stays on screen and appears once, and no request appears. With the untagged Google tag of Next.js with Google Consent Mode v2 and next/third-parties, cookielesscollectrequests withgcs=G100appear instead. The Application tab does not list a_gacookie until you accept. - Click the "I agree" button on the third route.
collectrequests appear without a reload, withgcs=G111under Consent Mode when thetargetingcategory is in use, andgcs=G101without it. - Navigate to 2 more routes. One
collectrequest withen=page_viewappears per route, and the Console does not show arun() was already called on this pagewarning. Change the filter tocookie-consent, and no new request appears. - Open the Application tab, select Cookies and your site, tick "Show URL-decoded", and confirm that
cookie_consent_levelholds"tracking":true. - Click your cookie settings link on a route the app rendered after start. The Preferences Center opens on the "Your privacy" tab. Select the tab of the category you accepted, such as "Tracking cookies", and its switch reads "Active".
Remove debug: true before you go live. Fix a consent banner that appears unstyled with Ad Blockers and CSP Hide the Cookie Banner, and run the checks every installation needs with Check That Your Cookie Banner Works.