Google Analytics 4 (GA4) helps you understand how visitors use a website. But a fast analytics integration should also respect the visitor’s choice about tracking.
If you load gtag.js only after someone clicks Accept, Google Tag Assistant may initially report that it cannot find your Google tag. That does not necessarily mean your Astro site is broken. It may be an expected outcome of Basic Consent Mode, where Google tags remain blocked before consent.
This tutorial builds a small, consent-first GA4 integration for an Astro website, explains the four Google Consent Mode v2 signals, and provides a practical browser testing plan. The code is a reference implementation rather than a compliance certification or a tested change to any live website.
1. Understand Basic and Advanced Consent Mode
Google describes two deployment patterns:
| Behavior | Basic Consent Mode | Advanced Consent Mode |
|---|---|---|
| Google tag before consent | Blocked | Loaded with denied defaults |
| Information sent before consent | No Google-tag transmission | Limited cookieless signals can be sent |
| After analytics consent | Load tag and measure | Update consent state and measure |
| Trade-off | Strong pre-consent blocking | Additional measurement/modeling signals |
This article implements Basic Consent Mode: don’t insert the Google tag until the user explicitly allows analytics. It is a good fit for site owners who want to minimize pre-consent analytics requests.
Basic and advanced are implementation patterns, not legal classifications. Your obligations depend on location, purpose, applicable laws, and other services on the site.

Figure 1. Basic mode blocks Google’s tag before a decision; advanced mode runs consent-aware tags with denied defaults.
2. Understand the Four Consent Mode v2 Parameters
Google Consent Mode v2 uses these commonly relevant parameters:
analytics_storage: controls analytics-related storage.ad_storage: controls advertising-related storage.ad_user_data: controls consent for sending user data to Google for advertising.ad_personalization: controls personalized advertising.
These are distinct permissions. Accepting website analytics does not automatically mean agreeing to advertising or remarketing.
For a website that needs GA4 analytics only, our example keeps all advertising signals at denied, even when analytics is accepted.
The code uses a site-specific consent preference saved in localStorage. That preference is not a substitute for a consent management platform (CMP) when your obligations or vendor stack require one.
3. Decide Where the Component Belongs in Astro
Place the consent component once in your shared base layout, not inside every page template. A typical structure is:
src/
components/
AnalyticsConsent.astro
layouts/
BaseLayout.astro
Your layout should render the component only once per page. Do not keep another unguarded GA4 snippet in your <head>, a tag manager, a plugin, or a third-party widget; otherwise the browser could contact Google before permission is granted.
The example below uses is:inline so Astro emits the browser script as written. The component uses only plain JavaScript and makes its own decision about when to load gtag.js.
4. Create the Consent Component
Create src/components/AnalyticsConsent.astro:
---
interface Props {
measurementId: string;
}
const { measurementId } = Astro.props;
---
<div id="analytics-consent" hidden role="region" aria-label="Analytics consent">
<p>May we use optional analytics cookies to understand site traffic?</p>
<button type="button" id="accept-analytics">Accept analytics</button>
<button type="button" id="reject-analytics">Reject</button>
</div>
<button type="button" id="analytics-preferences">Cookie preferences</button>
<script is:inline define:vars={{ measurementId }}>
(() => {
const storageKey = 'site-analytics-consent-v1';
const banner = document.getElementById('analytics-consent');
const accept = document.getElementById('accept-analytics');
const reject = document.getElementById('reject-analytics');
const preferences = document.getElementById('analytics-preferences');
let loaded = false;
function readPreference() {
try {
const value = localStorage.getItem(storageKey);
return value === 'granted' || value === 'denied'
? value
: null;
} catch {
return null;
}
}
function savePreference(value) {
try {
localStorage.setItem(storageKey, value);
} catch {
// Without persistent storage, ask again on the next visit.
}
}
function startAnalytics() {
if (loaded) return;
loaded = true;
window.dataLayer = window.dataLayer || [];
window.gtag = window.gtag || function () {
window.dataLayer.push(arguments);
};
// Initialize consent before configuring the Google tag.
window.gtag('consent', 'default', {
analytics_storage: 'denied',
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied'
});
window.gtag('consent', 'update', {
analytics_storage: 'granted',
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied'
});
window.gtag('js', new Date());
window.gtag('config', measurementId);
const script = document.createElement('script');
script.async = true;
script.src = 'https://www.googletagmanager.com/gtag/js?id=' +
encodeURIComponent(measurementId);
document.head.appendChild(script);
}
function choose(value) {
const previouslyGranted = readPreference() === 'granted';
savePreference(value);
banner.hidden = true;
if (value === 'granted') {
startAnalytics();
} else if (previouslyGranted && loaded) {
// Reload without injecting the Google tag again.
// Additional cookie deletion/withdrawal behavior may be needed.
window.location.reload();
}
}
accept.addEventListener('click', () => choose('granted'));
reject.addEventListener('click', () => choose('denied'));
preferences.addEventListener('click', () => {
banner.hidden = false;
});
const preference = readPreference();
if (preference === 'granted') startAnalytics();
if (preference === null) banner.hidden = false;
})();
</script>
How the sequence works: Before the visitor chooses, the page contains no Google tag request from this component. After Accept, it creates the dataLayer, queues a denied default followed by a granted analytics update, then loads gtag.js and configures the measurement ID. Advertising consent stays denied.
The component does not provide a full CMP, granular advertising choices, consent receipts, region rules, or deletion of previously created cookies. It also assumes ordinary full page loads; sites using Astro client-side navigation must re-test routing and page-view behavior.
Accessibility and design
Style the banner with your existing Tailwind/CSS design system and ensure it is keyboard accessible, readable on mobile, and does not misrepresent the choices. Both Accept and Reject should be easy to use. Avoid implementing a deceptive interface that pressures consent.
5. Add It to the Base Layout
In your existing BaseLayout.astro (or equivalent), insert it near the end of <body>:
---
import AnalyticsConsent from '../components/AnalyticsConsent.astro';
const gaId = import.meta.env.PUBLIC_GA_MEASUREMENT_ID;
---
<!-- Existing site layout content -->
{gaId && <AnalyticsConsent measurementId={gaId} />}
Define the public measurement ID as an environment variable for local development and your deployment platform:
PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX
A GA4 measurement ID is not a credential. The prefix PUBLIC_ makes it available in client-capable Astro code. Do not store API secrets in public environment variables.
This is an example insertion into an existing layout, not a complete replacement layout. Preserve your SEO head tags, existing navigation, footer, and page components.
6. Test the Three Consent States
Use a fresh private browsing session and browser DevTools → Network. Filter for google, gtag, collect, and googletagmanager.
| Scenario | Expected behavior from this implementation |
|---|---|
| First visit, no choice | Consent banner displayed; this component does not request gtag.js |
| Click Reject | Preference saved; no Google tag request from this component |
| Click Accept | Google script loads; GA4 should initialize if the network and configuration permit it |
| Reload after Accept | Stored permission restores analytics |
| Change Accept → Reject | Page reloads without reinserting this component’s tag |
Important: a third-party script, another GA integration, browser extension, or embedded widget could still make Google requests. Verify the entire page, not only this component.

Figure 2. A network-level checklist to confirm that tracking starts only after analytics permission.
7. Check Google Tag Assistant and GA4 Realtime
Open Google Tag Assistant and start a session with your deployed site.
With Basic Consent Mode, Tag Assistant may initially be unable to attach while the Google tag is blocked. Google explicitly notes that you may need to interact with the consent banner and accept before the tag can connect.
After accepting:
- Confirm that the correct Google measurement ID is present.
- Inspect the consent default and update events if available.
- Check
analytics_storageis granted but advertising fields remain denied in this example. - Visit a few pages and watch GA4 → Reports → Realtime.
- If needed, use DebugView with debugging configured; a normal Realtime report is not itself a code-level audit.
Do not treat a temporary setup warning as proof that data collection is broken. Conversely, the presence of a tag does not prove that page_view is recorded correctly.
8. Understand Why Tag Detection May Fail
When the tag is deliberately absent until opt-in, Google’s unattended checks may not observe it. Other possible reasons include an incorrect measurement ID, a blocked network, browser extensions, deployment caching, or a second script conflicting with your configuration.
Troubleshoot in this order:
- Confirm the site contains the consent banner.
- Check that
gtag.jsis absent before opt-in. - Accept consent and check that the Google tag request occurs.
- Check the requested ID matches the intended GA4 data stream.
- Verify
page_viewin Realtime and, if needed, DebugView. - Repeat on an actual deployed site, not only
localhost.
This investigation is more informative than deleting the banner simply to improve a dashboard status indicator.
9. Special Cases: Client-Side Navigation, Consent Withdrawal, and CSP
Astro View Transitions / ClientRouter. If your site uses client-side navigation, a script placed in a shared layout may not rerun with every navigation. You must explicitly test page-view tracking and determine whether manual page_view events are needed. Avoid sending both automatic and manual page views for one navigation.
Withdrawal of consent. Our small demo saves the new preference and reloads, so it does not inject GA4 again on the next page. But it does not erase previously set GA cookies, synchronize decisions across existing tabs, or manage other vendors. A production consent solution should implement and verify any required withdrawal and data-erasure behavior.
Content Security Policy. Restrictive CSP rules may block is:inline scripts or Google tag requests. A strict CSP setup requires nonces/hashes or another approved script strategy; do not disable CSP wholesale to make analytics work.
Server-side and third-party tracking. This client-side example does not govern Cloudflare Web Analytics, server access logs, Google Ads, embedded videos, or unrelated scripts. Inventory all data collection technologies on the site.
10. Test for Double Counting and Performance Regressions
After enabling analytics consent, compare a fresh visit and a return visit. Confirm that page_view is not sent twice due to duplicate snippets, site navigation handling, or multiple tag managers.
Measure performance separately for before consent and after consent. Delaying a third-party analytics script can reduce early JavaScript work, but it does not guarantee a particular Lighthouse score. Track actual impact with repeat tests under comparable conditions.
Avoid changing your Astro build, image pipeline, or CDN settings unless the observed data points to those components.
11. Production QA Checklist
- No unguarded second copy of GA4 exists.
- First-visit visitors can accept and reject analytics.
- Before consent, this implementation makes no Google tag request.
- Consent Mode v2 signals are sent in the intended order after opt-in.
- Advertising consent is not inferred from analytics consent.
- GA4 receives page views only after the intended permission.
- Return visits respect the stored preference.
- Withdrawal behavior is implemented and tested for the site’s obligations.
- Mobile and keyboard navigation work.
- Astro client-side navigation does not duplicate page views.
- All third-party embeds and tags have been audited.
- Privacy-policy wording accurately describes site behavior.
12. Frequently Asked Questions
Is a GA4 “tag not detected” warning always an error?
No. In Basic Consent Mode, Google tags are intentionally blocked until a user interacts with the consent banner. Inspect the tag and events after opt-in.
Is Basic Consent Mode the same as having no tracking?
Before opt-in, Basic Consent Mode blocks Google’s tag traffic. After opt-in, GA4 can measure according to the allowed consent categories and configuration.
Does Consent Mode replace the consent banner?
No. Consent Mode communicates and enforces consent states for Google tags; a separate user interface or CMP collects and manages visitor preferences.
Can I keep Google Ads permissions denied?
Yes. Analytics storage and advertising consent are separate choices. This tutorial does not enable ads-related consent.
Does this code guarantee GDPR compliance?
No. Compliance involves additional considerations such as geographic scope, notice wording, vendor disclosures, record keeping, data retention, and other tracking technologies. Seek qualified advice where appropriate.
Why does Tag Assistant show a blank consent view?
If Google tags have never loaded because consent has not been given, Tag Assistant may not have consent events to inspect. Start with a clean session, interact with the banner, and inspect the resulting events.
13. Final Thoughts
For an Astro blog, implementing privacy-first GA4 does not need to require a heavy JavaScript framework. A small, carefully placed consent component can keep Google’s tag blocked before opt-in and load it after a visitor grants analytics permission.
The harder part is verification: confirming the tag fires only at the intended time, GA4 receives page views, no duplicate integration exists, and withdrawal works as promised.
Prioritize correct visitor choices and measurable behavior over clearing an automated “tag not detected” warning at any cost.

Figure 3. Verify consent decisions, network activity, GA4 Realtime, and production deployment as separate checks.
Continue Reading
Note: The earlier GA4 tutorial demonstrates the basic analytics installation. For consent-first websites, use the approach in this guide instead of loading GA4 unconditionally.
Official References
- Google: Consent Mode overview
- Google: Set up Consent Mode
- Google: Verify Consent Mode
- Astro: Scripts and event handling
Editorial note: This is a reference implementation with illustrative configuration. It has not been applied to or tested on the author’s production site in this tutorial. Test your complete tag inventory and legal requirements before deployment.






