BuildWithMatija
  1. Home
  2. Blog
  3. Next.js
  4. Postmortem: Google Analytics Consent Race Condition in Next.js

Postmortem: Google Analytics Consent Race Condition in Next.js

How a React hydration timing bug caused GA4 to drop 100% of consenting user data with npa=1 and gcs=G100 — and the…

16th October 2026·Updated on:17th November 2026·MŽMatija Žiberna·
Next.js
Postmortem: Google Analytics Consent Race Condition in Next.js

⚡ Next.js Implementation Guides

In-depth Next.js guides covering App Router, RSC, ISR, and deployment. Get code examples, optimization checklists, and prompts to accelerate development.

No spam. Unsubscribe anytime.

Related Posts:

  • •Next.js Cookie Consent Banner: Build GDPR-Compliant System (No Libraries)
  • •Optimize Google Analytics with Tag Manager in Next.js 15
  • •PostHog Next.js Setup: GDPR-Compliant Analytics Guide
📄View markdown version
0

Comments

About the author

Matija Žiberna

Matija Žiberna

Full-stack developer, co-founder

AboutResume

Self-taught full-stack developer sharing lessons from building software and startups.

I'm Matija Žiberna, a self-taught full-stack developer and co-founder passionate about building products, writing clean code, and figuring out how to turn ideas into businesses. I write about web development with Next.js, lessons from entrepreneurship, and the journey of learning by doing. My goal is to provide value through code—whether it's through tools, content, or real-world software.

You might be interested in

Next.js Cookie Consent Banner: Build GDPR-Compliant System (No Libraries)
Next.js Cookie Consent Banner: Build GDPR-Compliant System (No Libraries)

19th July 2025

Optimize Google Analytics with Tag Manager in Next.js 15
Optimize Google Analytics with Tag Manager in Next.js 15

25th October 2025

PostHog Next.js Setup: GDPR-Compliant Analytics Guide
PostHog Next.js Setup: GDPR-Compliant Analytics Guide

20th July 2026

Contents

  • Executive Summary
  • Timeline
  • Initial State (Unknown - Pre-Incident)
  • Incident Discovery
  • Fix Attempt #1: React State Optimization
  • Fix Attempt #2: Inline Script in Component
  • Fix Attempt #3: Raw Script Tags in Layouts ✅
  • Fix Attempt #4: Complete Consent Grant ✅
  • Root Cause Analysis
  • The Problem: Race Condition in Client-Side Initialization
  • Technical Details
  • The Fix
  • Phase 1: Move Consent to Raw Script Tags
  • Phase 2: Grant Complete Ad Consent
  • Impact Assessment
  • Before Fix
  • After Fix
  • Affected Metrics
  • Lessons Learned
  • What Went Well
  • What Went Wrong
  • What We Learned
  • Prevention Measures
  • Immediate Actions Taken
  • Recommended Future Safeguards
  • Technical Reference
  • Google Consent Status Codes (`gcs`)
  • No Personalized Ads Flag (`npa`)
  • Consent Mode Parameters
  • Files Changed
  • Core Fix (Phase 1 - Race Condition)
  • Complete Fix (Phase 2 - Ad Consent)
  • Git History
  • References
  • Conclusion
On this page:
  • Executive Summary
  • Timeline
  • Root Cause Analysis
  • The Fix
  • Impact Assessment
Build with Matija logotip

Build with Matija

Complex B2B websites, headless CMS platforms, AI workflows, and internal systems designed and built with Next.js and Payload CMS.

Services

  • B2B Website Development
  • CMS Architecture Review & Platform Blueprint
  • Next.js + Payload Advisory
  • AI Integration & Implementation

Resources

  • CMS Hub
  • B2B Website Strategy
  • E-commerce Hub
  • Blog
  • Case Studies
  • About Matija

Payload CMS

  • Payload CMS Developer
  • Payload CMS Migration
  • Payload CMS Demos
  • All Payload CMS Resources

Discuss your project

Planning a rebuild, migration, application, workflow change, or platform decision? Start with the business problem and the system behind it.

Book a discovery callContact me →
© 2026Build with Matija•Vse pravice pridržane•Politika zasebnosti•Pogoji uporabe
BuildWithMatija
Get In Touch

Date: 2025-11-24 Severity: Critical (SEO Impact) Status: Resolved Duration: Unknown start → Fixed 2025-11-24


Executive Summary

A critical race condition in Google Analytics consent initialization caused 100% of analytics data to be discarded by Google due to privacy compliance flags. (If you are building the banner itself, see my Next.js GDPR cookie consent banner guide and Google Analytics with Tag Manager setup.) The issue manifested as npa=1 (No Personalized Ads) in all GA4 network requests, even when users had explicitly granted consent via the cookie consent banner. This resulted in:

  • Complete loss of analytics data from consenting users
  • SEO impact due to missing user behavior signals
  • Business intelligence gaps preventing data-driven decisions
  • Potential revenue loss from inability to track and optimize conversions

The root cause was a timing issue where Google Analytics initialized and sent pageview events before the consent state was read from the cookie, defaulting to "denied" consent mode.


Timeline

Initial State (Unknown - Pre-Incident)

  • Google Analytics consent implementation using React useEffect hooks
  • Consent state managed via React component state
  • Cookie consent banner functioning correctly
  • Users able to accept/reject analytics

Incident Discovery

  • Issue Detected: Network logs showed npa=1 on all GA4 requests
  • Indicator: gcs=G100 (analytics denied, ad storage denied)
  • Impact: Google discarding all analytics data for privacy compliance
  • User Report: "Your traffic is being thrown in the trash"

Fix Attempt #1: React State Optimization

  • Action: Moved consent check earlier in React component lifecycle
  • Result: Failed - still showing npa=1
  • Root Cause: React state updates are asynchronous; GA4 scripts loaded simultaneously

Fix Attempt #2: Inline Script in Component

  • Action: Added inline <Script> tag with consent initialization before gtag loads
  • Implementation: Used Next.js Script component with strategy="afterInteractive"
  • Result: Failed - still showing npa=1
  • Root Cause: All scripts with same strategy load simultaneously, no guaranteed order

Fix Attempt #3: Raw Script Tags in Layouts ✅

  • Action: Added raw <script> tags directly in server-rendered layouts
  • Implementation: Script executes immediately on HTML parse, before React hydration
  • Result: Partial Success - gcs=G101 (analytics granted, ads denied)
  • Outcome: Analytics tracking restored, but ads still blocked

Fix Attempt #4: Complete Consent Grant ✅

  • Action: Updated consent to grant all advertising parameters
  • Implementation: Added ad_storage, ad_user_data, ad_personalization
  • Result: Complete Success
  • Outcome: gcs=G111 (all consent granted), npa=0 or no npa parameter

Root Cause Analysis

The Problem: Race Condition in Client-Side Initialization

What Went Wrong:

  1. React Lifecycle Timing

    • Initial implementation used useState and useEffect to check consent
    • React state initialization is asynchronous
    • GA4 scripts loaded via Next.js Script component
    • No guaranteed execution order
  2. Script Loading Strategy

    • Multiple <Script> components with strategy="afterInteractive"
    • All scripts in this category load simultaneously
    • Consent initialization script raced with gtag.js and config scripts
    • gtag('config') often fired before gtag('consent', 'update')
  3. Default Consent Mode

    • Google Analytics defaults to "denied" for privacy compliance
    • When pageview fired before consent update, it sent npa=1
    • Google's servers received "denied" signal and discarded data
    • Subsequent consent updates couldn't retroactively fix initial pageview

Technical Details

Diagram

The Fix

Phase 1: Move Consent to Raw Script Tags

Added server-rendered <script> tags in layout files that execute before React hydration:

Files Modified:

  • src/app/(non-intl)/layout.tsx
  • src/app/(intl)/[locale]/layout.tsx

Implementation:

javascript
<script
  dangerouslySetInnerHTML={{
    __html: `
      (function() {
        window.dataLayer = window.dataLayer || [];
        function gtag(){window.dataLayer.push(arguments);}
        window.gtag = gtag;

        // Set default consent to denied
        gtag('consent', 'default', {
          'analytics_storage': 'denied',
          'ad_storage': 'denied'
        });

        // Immediately check cookie and update consent
        try {
          var cookie = document.cookie.split('; ')
            .find(function(row) { return row.startsWith('cookie_consent='); });

          if (cookie) {
            var value = JSON.parse(decodeURIComponent(cookie.split('=')[1]));
            if (value.analytics === true && value.consentGiven === true) {
              gtag('consent', 'update', {
                'analytics_storage': 'granted',
                'ad_storage': 'granted',
                'ad_user_data': 'granted',
                'ad_personalization': 'granted'
              });
            }
          }
        } catch(e) {
          console.error('Error reading consent cookie:', e);
        }
      })();
    `,
  }}
/>

Why This Works:

  • Raw <script> tags in SSR HTML execute in document order
  • Runs before any React code
  • Synchronous cookie reading (no async delays)
  • Consent set before GA4 initialization

Phase 2: Grant Complete Ad Consent

Updated all consent touchpoints to grant full advertising consent when analytics is accepted:

Files Modified:

  • src/app/(non-intl)/layout.tsx - Initial consent in raw script
  • src/app/(intl)/[locale]/layout.tsx - Initial consent in raw script
  • src/components/analytics/ga4-consent.tsx - Dynamic consent updates
  • src/lib/cookies/client-cookie-utils.ts - Programmatic consent updates

Consent Parameters Granted:

  • analytics_storage: 'granted' - Core analytics tracking
  • ad_storage: 'granted' - Advertising cookies
  • ad_user_data: 'granted' - User data for ads
  • ad_personalization: 'granted' - Personalized advertising

Before: gcs=G101 → Analytics OK, Ads Denied → npa=1 After: gcs=G111 → Everything Granted → npa=0


Impact Assessment

Before Fix

  • ❌ 100% data loss from consenting users
  • ❌ npa=1 on all requests
  • ❌ Google discarding analytics data
  • ❌ No user behavior insights
  • ❌ No conversion tracking
  • ❌ No remarketing capability

After Fix

  • ✅ Full analytics tracking restored
  • ✅ npa=0 or parameter removed
  • ✅ Google processing all data
  • ✅ User behavior insights available
  • ✅ Conversion tracking functional
  • ✅ Remarketing enabled

Affected Metrics

  • Users: All users who accepted analytics consent
  • Duration: Unknown (potentially weeks/months)
  • Data Loss: Irreversible for historical period
  • Business Impact: High - inability to make data-driven decisions

Lessons Learned

What Went Well

  1. Quick Diagnosis: Network logs clearly showed the npa=1 flag
  2. Iterative Fixing: Each attempt provided more information
  3. Comprehensive Solution: Fixed all consent touchpoints
  4. Documentation: This postmortem captures the full journey

What Went Wrong

  1. Initial Architecture: Over-reliance on React lifecycle for critical initialization
  2. Assumption About Script Ordering: Assumed Next.js Script strategy would guarantee order
  3. Incomplete Testing: Didn't validate network requests in development
  4. Monitoring Gap: No alerts for npa=1 or consent mode issues

What We Learned

  1. Critical Initialization Must Be Synchronous: Don't use React state/effects for blocking operations
  2. Script Execution Order Matters: Raw <script> tags are more predictable than Script components
  3. Test Network Traffic: Always validate actual requests, not just UI behavior
  4. Google's Privacy Defaults: GA4 defaults to "denied" - must set consent before config
  5. Consent Mode Signals: Understanding gcs and npa parameters is critical

Prevention Measures

Immediate Actions Taken

  1. ✅ Moved consent initialization to raw script tags
  2. ✅ Added synchronous cookie reading
  3. ✅ Granted complete advertising consent
  4. ✅ Updated all consent touchpoints

Recommended Future Safeguards

1. Monitoring & Alerts

  • Add GA4 data quality monitoring
  • Alert on unexpected drops in traffic
  • Monitor npa parameter in production logs
  • Track gcs consent status codes

2. Testing Procedures

  • Add E2E tests for consent flow
  • Validate network requests in CI/CD
  • Test with and without consent cookies
  • Verify consent mode in staging before deploy

3. Documentation

  • Document consent architecture
  • Add inline comments explaining timing requirements
  • Create runbook for consent debugging
  • Document Google Consent Mode v2 requirements

4. Code Reviews

  • Review checklist for analytics changes
  • Require network log validation
  • Flag any async consent operations

5. Development Environment

  • Add development tools to inspect consent state
  • Console logging for consent mode changes
  • Visual indicator of current consent status

Technical Reference

Google Consent Status Codes (gcs)

Format: G[analytics][ad_storage][additional]

CodeAnalytics StorageAd StorageMeaning
G100DeniedDeniedNo tracking allowed
G101GrantedDeniedAnalytics only, no ads
G110DeniedGrantedAds only (rare)
G111GrantedGrantedFull tracking enabled

No Personalized Ads Flag (npa)

ValueMeaningImpact
npa=1DeniedGoogle discards data, no tracking
npa=0GrantedGoogle processes data normally
(absent)GrantedGoogle processes data normally

Consent Mode Parameters

ParameterPurposeRequired For
analytics_storageCore analytics trackingPageviews, events, conversions
ad_storageAdvertising cookiesRemarketing, attribution
ad_user_dataUser data for adsAudience building
ad_personalizationPersonalized adsCustom ad targeting

Files Changed

Core Fix (Phase 1 - Race Condition)

  • src/app/(non-intl)/layout.tsx - Added raw script tag for immediate consent
  • src/app/(intl)/[locale]/layout.tsx - Added raw script tag for immediate consent
  • src/components/analytics/ga4-consent.tsx - Simplified to load scripts only

Complete Fix (Phase 2 - Ad Consent)

  • src/app/(non-intl)/layout.tsx - Grant all ad consent parameters
  • src/app/(intl)/[locale]/layout.tsx - Grant all ad consent parameters
  • src/components/analytics/ga4-consent.tsx - Update dynamic consent with ads
  • src/lib/cookies/client-cookie-utils.ts - Grant ads in cookie setter

Git History

code
1c38dce fix: grant ad_storage consent when analytics is accepted
8719ac6 fix: move consent initialization to raw script tags in layouts
ad34912 fix: resolve race condition in GA4 consent initialization

References

  • Google Consent Mode v2 Documentation
  • GA4 Consent Mode Implementation
  • Understanding npa Parameter
  • Next.js Script Component

Conclusion

This incident highlighted the critical importance of timing in consent mode implementation. What appeared to be a simple "read cookie and update consent" operation revealed itself to be a complex race condition requiring deep understanding of:

  1. Browser script execution order
  2. React/Next.js lifecycle
  3. Google Analytics consent architecture
  4. Privacy-by-default behavior

The fix required moving from React-based asynchronous initialization to synchronous, server-rendered script execution. This ensures consent is set before any tracking occurs, maintaining user privacy while enabling proper analytics when consent is granted.

Key Takeaway: Critical initialization that affects data integrity must happen synchronously and as early as possible in the page load lifecycle. React components are not appropriate for this type of blocking operation.


Document Owner: Development Team Last Updated: 2025-11-24 Next Review: After 30 days of monitoring post-fix

Comments