DEV Community

Anja Beisel
Anja Beisel

Posted on

Google Consent Mode Explained (React + TypeScript)

Privacy-First Analytics for Modern Web Apps (Part 2)

To address the data-loss problem (see Part 1), Google introduced Consent Mode.

The goal is to allow analytics tags to load before consent, but with restricted behaviour.


What Advanced Consent Mode does

With Advanced Consent Mode:

User visits site
  ↓
Google tag loads
  ↓
Consent state = denied
  ↓
Cookieless pings sent
Enter fullscreen mode Exit fullscreen mode

These pings may contain:

  • page URL
  • timestamp
  • browser / device type
  • approximate region

But they do not set cookies.

Google uses these signals to estimate user behaviour.


Basic vs Advanced Consent Mode

Basic consent mode: Google Analytics loads only after consent

Advanced consent mode: Google tag loads immediately with restricted tracking


Implementing Basic Consent Mode (React + TypeScript)

Example cookie consent logic:

import ReactGA from "react-ga4"

export function enableAnalytics() {
  const GA_ID = process.env.REACT_APP_GA_ID

  if (GA_ID) {
    ReactGA.initialize(GA_ID)
  }
}
Enter fullscreen mode Exit fullscreen mode

Called when the user clicks Accept.


Implementing Advanced Consent Mode

Advanced Consent Mode uses the gtag consent API.

Default state:

window.gtag("consent", "default", {
  analytics_storage: "denied",
  ad_storage: "denied"
})
Enter fullscreen mode Exit fullscreen mode

When the user accepts:

window.gtag("consent", "update", {
  analytics_storage: "granted",
  ad_storage: "granted"
})
Enter fullscreen mode Exit fullscreen mode

When the user declines:

window.gtag("consent", "update", {
  analytics_storage: "denied"
})
Enter fullscreen mode Exit fullscreen mode

This allows the Google tag to operate in restricted cookieless mode.


Series: Privacy-First Analytics for Modern Web Apps

  1. Why Cookie Consent Breaks Your Analytics
  2. Google Consent Mode Explained (React + TypeScript)
  3. Ads, Tracking, and the Legal Reality in the EU and UK
  4. The Hybrid Analytics Architecture

About this series

This series is based on real-world work building CSSEXY, a visual UI platform where understanding user behaviour is essential for improving the product.

All articles are also available on CSSEXY and there in the Gallery.

Top comments (0)