Google Consent Mode Explained (React + TypeScript)
Source: Dev.to
Privacy-First Analytics for Modern Web Apps (Part 2)
To address the data‑loss problem discussed in Part 1, Google introduced Consent Mode. Its goal is to let analytics tags load before the user gives consent, but with restricted behavior.
Advanced Consent Mode flow
User visits site
↓
Google tag loads
↓
Consent state = denied
↓
Cookieless pings sentData sent in cookieless pings
- page URL
- timestamp
- browser / device type
- approximate region
These pings do not set cookies. Google uses the signals to estimate user behavior.
- Basic consent mode – Google Analytics loads only after consent.
- Advanced consent mode – Google tag loads immediately with restricted tracking.
Example cookie‑consent logic (React)
import ReactGA from "react-ga4";
export function enableAnalytics() {
const GA_ID = process.env.REACT_APP_GA_ID;
if (GA_ID) {
ReactGA.initialize(GA_ID);
}
}Call enableAnalytics() when the user clicks Accept.
Using the gtag Consent API
Default state (no consent)
window.gtag("consent", "default", {
analytics_storage: "denied",
ad_storage: "denied"
});When the user accepts consent
window.gtag("consent", "update", {
analytics_storage: "granted",
ad_storage: "granted"
});When the user declines consent
window.gtag("consent", "update", {
analytics_storage: "denied"
});These calls let the Google tag operate in a restricted, cookieless mode until consent is granted.
Related topics
- Why Cookie Consent Breaks Your Analytics
- Google Consent Mode Explained (React + TypeScript)
- Ads, Tracking, and the Legal Reality in the EU and UK
- The Hybrid Analytics Architecture
About the series
This series is based on real‑world work building CSSEXY, a visual UI platform where understanding user behavior is essential for improving the product. All articles are also available on CSSEXY in the Gallery.