Skip to content

fix(gtag): skip loading gtag.js when GA_MEASUREMENT_ID is unset - #2511

Open
anirudhpv wants to merge 1 commit into
googleanalytics:mainfrom
anirudhpv:fix/gtag-missing-measurement-id
Open

anirudhpv wants to merge 1 commit into
googleanalytics:mainfrom
anirudhpv:fix/gtag-missing-measurement-id

Conversation

@anirudhpv

Copy link
Copy Markdown

Problem

When the site is built without GA_MEASUREMENT_ID (local development, forks, preview builds), every page requests https://googletagmanager.com/gtag/js?id=undefined and configures gtag with an undefined measurement ID.

Cause

useGtag always calls gtag("config", process.env.GA_MEASUREMENT_ID!, ...) and injects the gtag.js script, with no check that the ID is set.

Fix

Return early from the default snippet when GA_MEASUREMENT_ID is unset. The dataLayer / gtag stub is still installed, so existing gtag() calls (page views, events) remain harmless no-ops. Builds that set the ID behave exactly as before.

How tested

  • yarn check-types: no new errors (the 3 existing errors on main are unrelated).
  • gatsby build succeeds.
  • On a fork deployment without GA_MEASUREMENT_ID, there is no gtag/js?id=undefined request.

Without a measurement ID, useGtag still configured gtag with an undefined ID and requested gtag/js?id=undefined. Keep the dataLayer stub so gtag() calls are harmless, but return before configuring and injecting the script.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant