Google Analytics with cookie consent on a Quarto site
Measure visitor traffic responsibly without firing trackers before reader opt-in
The problem
Adding analytics to a documentation site or technical blog seems trivial until you consider privacy rules and development noise:
- Unconditional tracking breaches privacy standards. Injecting a standard tracking script causes the browser to fetch third-party scripts and set tracking cookies (
_ga,_ga_*) the moment a page opens. Under EU GDPR/ePrivacy rules, non-essential cookies such as analytics generally need prior opt-in consent. - Preview noise pollutes production metrics. If your analytics tag is enabled in the default site configuration, every local build, automated CI render, and pull request preview logs page views into your production dashboard.
- Confusion between public IDs and secrets. Developers often treat Google Analytics Measurement IDs (
G-XXXXXXXXXX) as confidential secrets and attempt to hide them behind environment variables. In reality, client-side tracking IDs are embedded in plain text within page source by design.
The goal is to enable Google Analytics 4 (GA4) with a clear opt-in consent mechanism, while ensuring that local previews and automated builds generate no tracking requests.
The Quarto way: profiles and express consent
Quarto provides native support for both Google Analytics 4 and cookie consent management via its site metadata. Rather than baking the tracking configuration into the primary _quarto.yml, we isolate it in an environment profile:
# _quarto-live.yml (merged only when QUARTO_PROFILE=live)
website:
google-analytics:
tracking-id: "G-XXXXXXXXXX" # Public GA4 measurement stream ID
anonymize-ip: true
cookie-consent:
type: express # No tracking cookies until explicit opt-in
style: simple
palette: lightHow express consent functions
When cookie-consent: type: express is declared, Quarto does not inject an immediately executable analytics snippet. Instead, it rewrites the script tag roughly like this:
<script type="text/plain" cookie-consent="tracking">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX', { 'anonymize_ip': true});
</script>Because the MIME type is text/plain, the browser refuses to execute the script during initial page parsing. The bundled consent library (served from site_libs/cookie-consent/) activates scripts marked cookie-consent="tracking" once the visitor opts in, and records the choice in a cookie_consent_level cookie.
Hold back the loader too
Quarto’s google-analytics: option holds back only the configuration snippet. It also emits the loader as an ordinary script, <script async src="https://www.googletagmanager.com/gtag/js?id=...">, so the browser requests it from Google on every page load, before the visitor has chosen anything.
The consent library can hold that back as well. When a visitor accepts a category, it recreates each text/plain script marked with that category as a real script and copies its src. So we stopped using Quarto’s google-analytics: option and load GA4 from an include, with both scripts marked:
# _quarto-live.yml
website:
cookie-consent:
type: express
style: simple
palette: light
format:
html:
include-in-header: _includes/analytics.html<!-- _includes/analytics.html -->
<script type="text/plain" cookie-consent="tracking" async
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script type="text/plain" cookie-consent="tracking">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX', { 'anonymize_ip': true });
</script>The include sits in the live profile, so previews and local renders stay free of analytics as before.
Gating analytics in GitHub Actions
To keep pull request previews and local renders free of tracking tags, configure your CI workflow to activate the live profile only on merges to your primary branch:
# .github/workflows/quarto.yml
env:
QUARTO_PROFILE: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && 'live' || '' }}During a pull request build or local quarto render, QUARTO_PROFILE remains empty. Quarto reads only _quarto.yml, producing static HTML with no Google Analytics tags and no consent banner. When code merges into main, Quarto overlays _quarto-live.yml and produces the production build.
What we observed
We tested this configuration across local builds, pull requests, and live dev hosting on 2026-09-26:
- Local and PR builds are sterile. Inspecting the rendered HTML of a PR preview showed no occurrences of
googletagmanagerorG-. No tracking code was present in the deployment. - Opt-in operates as designed. On the live deployment, visiting the site presented the consent banner. Inspection of browser storage confirmed that
cookie_consent_levelwas initialised withtracking:false. No_gacookies existed in the browser before consent was clicked. - A technical nuance on loader fetching. While Quarto blocks execution of the
gtagconfiguration snippet, the external loader (https://www.googletagmanager.com/gtag/js?id=...) is still fetched over the network on initial page load. While no persistent cookies are set before consent, the HTTP request itself reaches Google’s servers. For teams with strict no-external-traffic requirements prior to consent, the loader tag itself must be gated. We now gate it (see Hold back the loader too). - The gated loader, checked on 2026-09-27. We served a
liverender through the Firebase Hosting emulator, with the Measurement ID swapped for a test ID so no data reached the real stream. Before consent the browser made no request togoogletagmanager.com,gtagwas undefined and there were no_gacookies. After clicking I agree,gtag.jswas requested and the_gacookies appeared. After I decline (in a fresh cookie store), the next page made no request and set no_gacookies. - Banner copy wording. Quarto’s default banner text contains boilerplate mentioning third-party advertising cookies. Because an engineering site runs no advertising networks, this wording is inaccurate. The wording cannot be changed through Quarto’s
cookie-consentoptions (onlyprefs-textfor the preferences link is configurable), and we are tracking a fix (a custom include or another consent tool). - Measurement IDs are public. As shown in the HTML snippet above, the Measurement ID is visible to anyone inspecting page source. It does not require storage in a secret vault (see secrets management).
The R way: Shiny and pkgdown
The same principles of environment separation and consent gating apply to the wider R ecosystem.
Shiny applications
Shiny applications often track user sessions or tab navigation by inserting gtag() calls via tags$script(). Firing gtag("event", ...) as soon as server.R runs places tracking cookies on the user’s system without permission.
To implement equivalent express consent in Shiny: 1. Store a user consent state in a reactive value or browser cookie. 2. Render the analytics script conditionally inside an observeEvent() only after the user accepts a consent modal or banner. 3. Check Sys.getenv("R_CONFIG_ACTIVE") or configuration settings so local development runs never initialise the tracking client.
pkgdown documentation sites
R package authors frequently include analytics to measure documentation usage. In pkgdown, custom scripts are added to _pkgdown.yml using template.includes:
template:
includes:
in_header: |
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>Unlike Quarto, pkgdown does not offer an out-of-the-box cookie-consent engine. Adding raw gtag.js in in_header fires tracking immediately for every reader. If your package documentation must respect cookie consent, you cannot rely on a single YAML switch. You must either embed a third-party consent banner script in in_header or manually structure the tracking snippet to read a consent flag before invoking gtag('config').
Pitfalls we hit
- Expecting analytics in default local renders. Running
quarto previeworquarto renderwithout specifying--profile liverenders the base configuration. The banner will not appear. To test consent styling locally, runQUARTO_PROFILE=live quarto preview. - Assuming the loader is completely blocked. As noted in our observations, Quarto’s built-in express consent delays the config script but still loads the external
gtag.jsscript tag on initial render. Verify whether your organisation’s interpretation of privacy guidelines allows this external script fetch. - Default banner mentions non-existent ad trackers. Leaving default Quarto banner copy intact can suggest that technical documentation shares data with advertising partners. Because Quarto’s options do not expose banner text configuration, addressing this requires a custom include or alternative consent integration.
- Hiding Measurement IDs in CI secrets. Storing a public tracking ID in GitHub Secrets adds maintenance burden without reducing risk. Keep identifiers in repository variables or profile configuration files.
- 2026-09-26: Removed the end-of-post checklist.
- 2026-09-27: The
gtag.jsloader is now held back until consent too (a custom include instead of Quarto’sgoogle-analytics:option), with the browser check that shows it.