In Basic Consent Mode, Google tags should stay blocked until the visitor grants the relevant consent. Advanced Mode allows the Google tag to load under denied defaults, so a request in the Network panel does not always mean something has gone wrong.
Audit the Astro Site Before Installing CookieScript
Find out what your website already loads before adding CookieScript. Check shared layouts, components, integrations, middleware, API routes, server-rendered pages, authentication code, and imported analytics components. Search for terms that may reveal cookies, analytics, embeds, or marketing tools:
gtag— Google tag code or event callsgoogletagmanager— GTM and Google tag script URLsGoogleAnalytics— an analytics component or integrationG-— a GA4 Measurement ID, such asG-ABC1234567Astro.cookies— cookies read or set by Astro server codesession— Astro sessions or authentication session handlingiframe— content embedded from another siteyoutubeandvimeo— video embedsmaps— map embeds or location serviceschat— chat and customer-support widgetspixel— advertising or tracking pixels
Also search for the names of providers already used by the site. A YouTube URL inside an Astro component may be easier to miss than a file named analytics.astro.
Pay attention to server code. On-demand routes, API endpoints, and middleware can add cookies to the response. If Astro session storage is configured, Astro also sets a session-ID cookie when the session is first used. The session data itself remains in the configured session store.
Check What Loads Before Consent
Open the site in a private window and do not interact with the banner. In DevTools, check:
- Application → Storage → Cookies
- Application → Storage → local storage
- Network
In the Network panel, try filters such as collect, g/collect, gtm.js, gtag/js, doubleclick, facebook, youtube, and maps.
Open suspicious requests and check the domain, initiator, request cookies, response cookies, and timing. A request containing collect is not enough on its own to show which tool sent it or whether cookies were used.
Record What You Find
Record each tool as you find it, including where it loads, what it does, and how consent should control it.
Whether consent is required depends on the tool, its purpose, the site’s audience, and the law that applies.
Choose How to Install CookieScript
Use Google Tag Manager when GA4 and other consent-controlled tags already run through the GTM container.
Install CookieScript directly when the site does not use GTM. Direct installation is also required when CookieScript geo-targeting is enabled, because the geo-targeted banner code must be added directly to the page <head>.
Install the CookieScript banner once. Do not add the same banner directly and through GTM.
Add Google Tag Manager to the Shared Astro Layout
Add the GTM container once in the shared layout that provides the site-wide <head> and <body>.
Find the Site-Wide Layout
Common locations include:
src/layouts/Layout.astrosrc/layouts/BaseLayout.astrosrc/components/Layout.astro
These names are conventions, not Astro requirements. Follow the imports from files in src/pages when it is not clear which layout is site-wide. The correct file is the one that contains the shared page structure and renders page content through <slot />.
Add the GTM Container
Open the Install Google Tag Manager window in GTM and copy both snippets. Place the first inside <head>, as high as possible. Put the <noscript> block immediately after the opening <body> tag.
Replace GTM-XXXXXXX in both places with the same container ID.
---
const { title = "Astro Website" } = Astro.props;
---
<!doctype html>
<html lang="en">
<head>
<!-- Google Tag Manager -->
<script is:inline>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({
'gtm.start':new Date().getTime(),event:'gtm.js'});
var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');
</script>
<!-- End Google Tag Manager -->
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>{title}</title>
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript>
<iframe
src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0"
width="0"
style="display:none;visibility:hidden"
></iframe>
</noscript>
<!-- End Google Tag Manager (noscript) -->
<slot />
</body>
</html>
The is:inline directive prevents Astro from processing or bundling the GTM bootstrap code.
Because Astro inline scripts may run again during ClientRouter navigation, verify that the GTM bootstrap executes only once. If it runs again, make the installation idempotent or place it where ClientRouter does not re-execute it.
Check the Installation
Open the GTM workspace and select Preview. Enter the website URL and connect it to Tag Assistant. The session should show the expected container ID.
On the first page load, open the Network panel. In a standard installation, one gtm.js request should appear with the expected container ID. If it does not, also search for the container ID and any First-party Google Tag Gateway endpoint used by the site.
Search the project for the complete GTM ID as well. It should not also appear in an individual page, analytics component, second layout, or hosting integration. Remove any duplicate installation before continuing.
Install the CookieScript CMP Template in GTM
The CMP tag has three jobs here: load the CookieScript banner, set the initial consent state, and send an update after the visitor makes a choice.
Add the CookieScript Template
Open the web container in Google Tag Manager, then:
- Select Templates.
- Under Tag Templates, select Search Gallery.
- Search for
CookieScript. - Open the CookieScript CMP template.
- Select Add to workspace.
- Review the requested permissions, then select Add.
Open Tags, select New, then open Tag Configuration and choose the CookieScript template.
Enter the Cookie Banner script URL. Copy this value from the Installation tab of the relevant banner in the CookieScript dashboard. The field expects the URL used by the banner script, not the complete <script> element.
Review the default consent settings shown in the template. These values apply before the visitor accepts, rejects, or changes a category.
Use the latest version of the gallery template. GTM displays an update notice when a newer version is available.
Assign the Consent Initialization Trigger
Open the tag’s Triggering panel and select:
Consent Initialization – All Pages
The template does not receive this trigger automatically.
GTM runs Consent Initialization before its other trigger types. That gives the CMP tag time to establish the default consent state before the Google tag, GA4 events, or advertising tags are evaluated.
Do not use a normal Page View – All Pages trigger for the CMP tag. Do not attach unrelated analytics or advertising tags to Consent Initialization.
Save the tag.
Enable Consent Mode v2 in CookieScript
In the CookieScript dashboard, open the banner and go to:
Settings → Google Consent Mode
Enable ENABLE Google Consent Mode V2, save the setting, and save the banner.
CookieScript supports the four main Consent Mode v2 parameters:
ad_storage— controls storage used for advertisinganalytics_storage— controls storage used for analyticsad_user_data— controls whether advertising-related user data may be sent to Googlead_personalization— controls whether data may be used for personalized advertising
CookieScript also displays three additional storage types:
functionality_storagepersonalization_storagesecurity_storage
Review the Category Mappings
The template starts with these category mappings:
ad_storage→ Targetinganalytics_storage→ Performancead_user_data→ Advertisingad_personalization→ Advertisingfunctionality_storage→ Functionalitypersonalization_storage→ Functionalitysecurity_storage→ Functionality
These defaults are editable. Review each mapping against the services assigned to that banner category.
Changing a mapping changes which visitor choice controls the corresponding consent state. For example, analytics_storage becomes granted when the visitor accepts the category assigned to it.
Check the Order Before Publishing
Save the workspace changes, then select Preview. Enter the Astro site URL and connect Tag Assistant. Preview tests the unpublished workspace, so do this before publishing the container.
On the first page load:
- Confirm that the CookieScript CMP tag fires during Consent Initialization.
- Open the consent details in Tag Assistant.
- Check that the four main parameters already have default values.
- Confirm that those defaults appear before the Google tag or GA4 event tags run.
Make a choice in the banner. Tag Assistant should show a later consent event. The affected values should change to granted or remain denied, depending on the categories selected.
Configure GA4 Once
Use the GA4 Measurement ID found during the audit to trace the installation. Search for the complete ID, such as G-ABC1234567, in GTM, the Astro project, hosting settings, CMS integrations, and scripts that load only in production.
If the same property loads from both the shared Astro layout and GTM, remove one copy. For this setup, keep GA4 in GTM. Loading the same Google tag more than once can produce duplicate data or apply settings more than once.
Set the main Google tag to Initialization – All Pages. Do not assign it to Consent Initialization – All Pages, which should remain reserved for the CookieScript CMP tag.
Distinguish the Google Tag from Event Tags
The Google tag contains the GA4 destination and settings shared by Analytics tags. A Google Analytics: GA4 Event tag sends a named event such as page_view.
The duplicate to remove is another installation of the same Google tag, or the same event being sent through two different routes. For example, a page_view sent automatically and again by a separate event tag may be counted twice.
Set the Consent Checks for the Chosen Mode
Open each relevant tag in GTM and go to:
Advanced Settings → Consent Settings
Do not apply these instructions to the CookieScript CMP tag.
CookieScript implements Basic Mode by adding required consent checks to Google tags through Require additional consent for tag to fire. Google’s current guidance recommends removing additional consent checks from Google tags because they already have built-in consent handling.
If you use CookieScript’s Basic Mode method, treat it as a deliberate CookieScript-specific configuration. Verify in Tag Assistant that every affected Google tag remains blocked before consent and fires after the required consent is granted.
For Advanced Mode, leave Additional Consent Checks set to Not set for Google tags that use built-in consent handling.
Third-party tags without built-in consent handling may still need Require additional consent for tag to fire. Review them individually rather than applying one setting to the entire container.
Advanced Consent Mode may support modeled reporting, but it does not guarantee that every measurement gap will be recovered.
Handle GA4 Pageviews with Astro ClientRouter
Check Whether ClientRouter Is Enabled
Search the shared layout or head component for:
---
import { ClientRouter } from "astro:transitions";
---
<html>
<head>
<ClientRouter />
</head>
</html>
If the component is not present and every navigation loads a new document, the manual SPA setup below is not needed.
Test the Current Pageview Behaviour
Open GA4 DebugView and test the site before adding another pageview tag.
If Basic Consent Mode is active, grant analytics consent first. Then:
- Load the first page and confirm that one
page_viewappears. - Navigate to another route without reloading the tab.
- Count the new
page_viewevents. - Check
page_locationandpage_title.
The test may show no route-change event, two events, the previous URL, or the new URL with the previous title. Record the result before changing the setup.
Disable Automatic History-Based Pageviews
Disable GA4’s automatic browser-history option first.
GA4 → Admin → Data collection and modification → Data streams → Web stream → Enhanced measurement
Select the settings icon. Under Page views, open Show advanced settings and clear:
Page changes based on browser history events
Save the change.
Create a History Change Trigger
In GTM:
- Open Triggers and select New.
- Open Trigger Configuration.
- Select History Change.
- Choose All History Changes.
- Name the trigger
History Change. - Save it.
Create the Google Tag Update
Create a new Google tag and use the same Tag ID as the existing Google tag.
Under Configuration settings, add:
page_location→{{Page URL}}page_title→{{Page Title}}update→true
Name the tag Google Tag – SPA Update.
Do not assign a trigger.
Send the Route-Change Pageview
Create a Google Analytics: GA4 Event tag with:
- Measurement ID: the site’s GA4 Measurement ID
- Event Name:
page_view - Trigger:
History Change
Under Advanced Settings → Tag Sequencing:
- Enable Fire a tag before this tag fires.
- Select
Google Tag – SPA Update.
Save the event tag as GA4 Event – Virtual Page View.
Test the Unpublished Changes
Navigate through several ClientRouter routes and inspect the events in DebugView.
Each route change should send one page_view with:
- the current URL in
page_location; - the current page title in
page_title.
Astro may update document.title after the History Change trigger runs. If GA4 receives the new URL with the previous title, the pageview is being sent too early. Adjust the timing and test again before publishing.
Do not run this setup alongside automatic history-based pageviews, custom astro:page-load tracking, hard-coded route tracking, or another GTM tag sending the same page_view.
Direct CookieScript Installation Without GTM
Use direct installation when the Astro site does not use GTM.
Copy the Generated Code
Open the relevant banner in CookieScript and go to Install or Settings → Installation, depending on the dashboard version shown in the account.
Configure any geo-targeting rules before copying the code. The location rules form part of the generated snippet, so changing them later requires copying the updated code again.
Copy the complete banner code supplied by CookieScript. Do not recreate it from the script URL or edit its internal values.
Add It to the Shared Layout
Open the shared Astro layout identified earlier and paste the generated banner code into its <head>. Add it as the first banner script in the site-wide layout rather than inserting it into individual pages or components.
For a geo-targeted banner, keep the generated code directly in <head>. Do not move it into GTM.
If the CookieScript CMP template is already installed in GTM, remove that tag before using the direct method.
Preserve the Direct Consent Mode Setup
Direct Consent Mode validation requires the banner code, the default consent configuration, and the gtag.js setup to be present in the page header.
Use the complete manual Consent Mode configuration required for the direct installation. Inside the page <head>, preserve this order:
- the default consent-state code;
- the
gtag.jscode; - the CookieScript banner code;
- all other scripts.
Verify the Installation
In CookieScript, open Settings → Google Consent Mode and run Validate installation.
Start a Google Tag Assistant session. If Basic Mode initially blocks the Google tag, accept the required category so Tag Assistant can connect. Then inspect the earliest Consent event for the default values.
Make a banner choice and inspect the most recent Consent event for the update. The four main Consent Mode v2 parameters should reflect the selected categories.
Control Third-Party Scripts and Embeds
Use GTM for tags loaded through GTM and CookieScript for scripts or embeds written directly into Astro.
Tags Managed in GTM
If a tag already loads through GTM, leave its consent handling there. Do not also place the same resource under CookieScript automatic blocking. Using both systems against one script can create conflicts and duplicate scanning activity.
Scripts Loaded from Astro Code
Use CookieScript automatic blocking or its manual attributes for scripts placed directly in Astro layouts and components.
Banner visibility does not prove that those scripts are blocked. In the CookieScript dashboard, open the banner’s Scripts section and confirm that automatic blocking is enabled and configured.
Check that:
- the site has been scanned;
- the relevant script or service appears in the results;
- the correct consent category is assigned;
- blocking is enabled for that resource.
Run another scan when scripts or blocking settings have changed since the previous scan.
The CookieScript banner code must load before scripts that it is expected to block automatically.
Block a Direct Script Manually
Use this pattern for a script placed directly in an Astro layout or component:
<script
type="text/plain"
data-cookiescript="accepted"
data-cookiecategory="targeting"
src="https://example.com/script.js"
></script>
type="text/plain" stops the browser from treating the element as executable JavaScript during the initial page load.
data-cookiescript="accepted" gives CookieScript control over when the script becomes active.
data-cookiecategory="targeting" connects the script to a consent category. Replace targeting with the category assigned to the actual service. Other available values include strict, functionality, performance, and unclassified.
Replace the example URL with the real script URL.
Block an Iframe Manually
For a directly embedded video, map, or other external iframe, replace src with data-src:
<iframe
data-src="https://example.com/embed"
data-cookiescript="accepted"
data-cookiecategory="functionality"
></iframe>
Using data-src prevents the browser from requesting the embedded page immediately. Once the visitor accepts the assigned category, CookieScript can activate the iframe and load the external content.
Replace the example URL and category with the values required by the actual embed.
Review Cookies Set by Astro
CookieScript controls scripts in the browser. It cannot stop an Astro route, endpoint, or middleware function from adding a Set-Cookie header to the response.
Return to the server-set cookies found during the audit. For each one, decide whether it is necessary for the feature the visitor requested or whether the server should check consent before creating it.
Test the Full Consent Flow
Open two private sessions. Accept consent in one and reject it in the other. Do not reuse a session, because the stored choice can affect the next test.
- Only one banner should be shown on the first visit. When GEO-targeting is enabled, the banner should behave according to the rules set for both included and excluded regions.
- Acceptance and rejection should remain in place after navigation.
- Change one category from the preferences panel. The stored consent record should be updated, newly allowed tags should fire when their triggers occur, and tags requiring the newly denied category should stop on later triggers.
- Verify whether Reload page after a user allows/rejects cookies is enabled. If page reload is disabled, the consent update should not require one.
- After revoking consent for a previously granted category, check later tag activity, loaded embeds, existing cookies, and the stored consent record. Tags requiring the revoked category should not fire on later events. An iframe that has already loaded may remain until the site removes or replaces it.
HttpOnlyand third-party-domain cookies may remain. For GA4, confirm that existing analytics cookies are no longer read or updated. Other denied services should be checked for new or updated cookies.- Navigation with the internal ClientRouter should not start a new CookieScript instance or load a second GTM container.
Managing the Rest of the Consent Setup
The Astro and GTM configuration only covers part of the implementation. The remaining Cookie Consent work still needs to be configured in CookieScript, including tracking pixels, third-party scripts, blocking rules, consent records, and connected integrations.
CookieScript is a Google-certified Consent Management Platform with Gold tier status. This is particularly relevant when the Astro site uses Google advertising, analytics, or measurement products.
CookieScript CMP Features
The features available to a site depend on its CookieScript plan and the options enabled for the banner. Available features include:
- customizable cookie banner;
- automatic third-party script and cookie blocking;
- cookie scanning;
- visitor consent recording;
- Google Consent Mode v2 integration;
- Google Tag Manager integration;
- Global Privacy Control support;
- IAB TCF 2.3 integration;
- cross-domain and subdomain consent sharing;
- integrations for Wix, Shopify, Webflow, and other website platforms;
- CookieScript API;
- cookie banner sharing;
- Cookie Policy generator;
- Privacy Policy Generator.
CookieScript also provides a 14-day free trial of its Plus plan without requiring a credit card.
Final Thoughts
A minimal Astro site using only essential storage may not require this setup. However, the services used, the site’s audience, and the applicable legislation will determine whether that is the case. Audit the site first and add only the consent controls the implementation requires.
Frequently Asked Questions
Does every Astro website need a Cookie Consent banner?
No. Astro itself does not require a cookie consent banner. The need depends on the analytics tools, advertising tags, third-party cookies, optional cookies, audience, and applicable legislation connected to the website.
How do you add CookieScript to an Astro website?
CookieScript can be installed through Google Tag Manager or added directly to the shared Astro layout. Use GTM when analytics and other consent-controlled tags already run through the container. Use direct installation when the site does not use GTM or when GEO-targeting is enabled. The generated banner code and installation options are covered in the CookieScript Cookie Banner Set-Up Guide.
Which GTM trigger should the CookieScript CMP tag use?
The CookieScript CMP tag should use Consent Initialization – All Pages. This allows it to establish the default consent state before the Google tag, GA4 events, or advertising tags are evaluated. The main Google tag should use Initialization – All Pages. This ordering is part of the Google Consent Mode v2 setup.
How does Google Consent Mode v2 work with CookieScript?
Google Consent Mode v2 allows CookieScript to communicate the visitor’s consent choices to Google tags. CookieScript maps banner categories to parameters such as analytics_storage, ad_storage, ad_user_data, and ad_personalization. Initial values are set before the visitor makes a choice, and updated values are sent after the visitor changes their preferences. The behaviour also depends on whether the site uses Basic or Advanced Google Consent Mode.
How do you prevent duplicate GA4 pageviews with Astro ClientRouter?
Use one pageview method only. When manual Google Tag Manager route tracking is used, disable GA4’s automatic browser-history pageviews, create a History Change trigger, update page_location and page_title, and send one sequenced page_view event for each route change.
Can CookieScript block cookies set by Astro server code?
No. CookieScript can control browser-loaded scripts and automatically block third-party cookies and scripts, but it cannot stop an Astro route, endpoint, middleware function, session, or authentication service from returning a Set-Cookie header. Server-set cookies must be reviewed and controlled in the server logic that creates them.
How do you test CookieScript and Consent Mode v2 on an Astro site?
Use separate private browsing sessions to test acceptance, rejection, category changes, and consent withdrawal. Check Tag Assistant, GA4 DebugView, browser storage, and the Network panel. Confirm that consent defaults appear before dependent tags, updates follow the visitor’s choice, ClientRouter navigation sends one pageview, and neither CookieScript nor GTM loads twice. The Cookie Consent Banner Checklist provides additional checks for the banner and its connected consent tools.