# Add Google Analytics to a Gatsby Blog

Yes. An agent adds gatsby-plugin-google-gtag to your Gatsby 5 blog, reads the ID from an env file, respects Do Not Track, proves it with a build and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-analytics/gatsby/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the site before adding a plugin. In a blog shaped like gatsbyjs/gatsby-starter-blog, `package.json` pins `gatsby ^5.14.6`, `react ^18.1.0`, `gatsby-plugin-feed`, `gatsby-plugin-image`, `gatsby-plugin-manifest`, `gatsby-plugin-sharp`, `gatsby-source-filesystem`, `gatsby-transformer-remark` with `gatsby-remark-images`, `gatsby-remark-prismjs` and `gatsby-remark-responsive-iframe`, and `prettier ^2.8.8` as the only dev dependency; the scripts are `develop`, `build`, `serve`, `clean`, `format` and a `test` that prints `Write tests!` and exits 1. `gatsby-config.js` holds `siteMetadata` with `title`, `author`, `description`, `siteUrl` and a `social.twitter` handle, and the plugin array ending in `gatsby-plugin-feed` (an `/rss.xml` output) and `gatsby-plugin-manifest`. There is no analytics plugin, no `.env` file (the `.gitignore` already covers `.env*`) and no `dotenv` dependency; `gatsby-browser.js` only imports fonts, `normalize.css`, `style.css` and the Prism theme, and `gatsby-ssr.js` sets `lang` on the `html` element.

The official plugin for Google Analytics 4 is `gatsby-plugin-google-gtag`, so the agent installs it with `npm install` so `package-lock.json` changes once, and adds `dotenv` as a dependency because Gatsby does not load `.env` files on its own. At the top of `gatsby-config.js` it adds `require("dotenv").config({ path: `.env.${process.env.NODE_ENV}` })` and reads `process.env.GATSBY_GA_MEASUREMENT_ID`. The plugin entry sets `trackingIds` to that one id, `gtagConfig` with `anonymize_ip: true`, and `pluginConfig` with `head: true`, `respectDNT: true` and `exclude: ["/404/"]`. The entry is pushed onto the plugin array only when the variable is set, so `gatsby build` on a machine with no id still succeeds and the tag is simply absent; `.env.example` documents the variable with a `G-XXXXXXXXXX` placeholder.

Nothing in `src/` needs to change for pageviews: the plugin sends one on every route change and only runs in production builds. The agent does add one `window.gtag("event", ...)` call, wrapped in a `typeof window !== "undefined"` check, where the blog has a user action worth counting. In this starter there is none beyond the `rel="prev"` and `rel="next"` links in `src/templates/blog-post.js`, so it adds the call to those links with the target slug as a parameter, and says in the pull request that it is an example to copy, not a requirement.

The check is a real production build, because the plugin does nothing under `gatsby develop`. The agent runs `npm ci`, then `GATSBY_GA_MEASUREMENT_ID=G-TEST npm run build` and `npx gatsby serve`, fetches `/` and a post page from the served site, and greps the HTML for the `googletagmanager.com/gtag/js?id=G-TEST` script in `head` and the `gtag('config', 'G-TEST', {"anonymize_ip":true})` call; it then builds once more with the variable unset to show the markup contains no gtag at all. It runs `npm run format` so the new config follows `.prettierrc` (`semi: false`, `arrowParens: "avoid"`), and pastes the build summary and the two grep results.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "codex",
  "input": "Add Google Analytics 4 to this Gatsby blog and open a pull request. Read package.json, gatsby-config.js, gatsby-browser.js, gatsby-ssr.js, .gitignore, .prettierrc and src/templates/blog-post.js first. Install gatsby-plugin-google-gtag and dotenv with npm so package-lock.json is updated. In gatsby-config.js load .env.<NODE_ENV> with dotenv, read GATSBY_GA_MEASUREMENT_ID, and add the plugin only when it is set, with trackingIds set to that id, gtagConfig anonymize_ip true, and pluginConfig head true, respectDNT true and exclude /404/. Add .env.example with a G-XXXXXXXXXX placeholder. Add one guarded window.gtag event call on the previous and next post links in the blog post template as an example and say so in the pull request. Run npm run format, then build with GATSBY_GA_MEASUREMENT_ID=G-TEST, serve the build, fetch the index and one post page and show that the gtag script with that id is in the head and the config call has anonymize_ip; build again with the variable unset and show no gtag markup. Paste the build summaries and both checks. Do not change siteMetadata, the feed or the manifest plugins.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request with two dependency lines in `package.json` and their `package-lock.json` entries, a `dotenv` line and a conditional plugin entry in `gatsby-config.js`, a new `.env.example`, and a few lines in `src/templates/blog-post.js`. The description shows the `gatsby build` summary, the `head` markup from the served build with `G-TEST`, and the empty result from the build without the variable.

The starter has no CI workflow and its `test` script exits 1 by design, so the pasted build output is the check. On a site deployed from a host that builds on pull requests, the preview build is a second check, and will contain no tag until the variable is set there.

A reviewer confirms that the id comes only from the environment and is not committed, that `respectDNT` and `anonymize_ip` match the site's privacy notice, that the `/404/` exclusion is wanted, and whether to keep or drop the example event. Then they set `GATSBY_GA_MEASUREMENT_ID` in the host's build environment.

## Run it on every new site from the starter

A team that runs several Gatsby sites sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `gatsby-config.js`, so a site that already loads `dotenv` or uses `gatsby-plugin-google-analytics` (the Universal Analytics plugin) gets the GA4 plugin added or swapped in without a second env loader, and each opens its own pull request. Send a `request_id` with each call so a retry does not start a second run.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from, so the variable can be set per site once its pull request is merged.

## Why run it on Rush?

Analytics plugins are configured once and checked never: `gatsby develop` shows nothing because the tag only ships in production, so the usual verification is deploying and waiting a day for data. In a Rush sandbox the agent runs the real production build, serves it, and reads the markup for the script and the config call, with and without the id, and that output stays in the run's record beside the diff.

The change itself is small, but doing it right means an env loader, a conditional entry so builds without the id still pass, a documented variable and a format pass, which is a half hour of care per site. The agent does it in one pass and the same request works unchanged on the next blog.

## Frequently asked questions

### Why gatsby-plugin-google-gtag and not gatsby-plugin-google-analytics?

Because `gatsby-plugin-google-analytics` targets Universal Analytics, which Google has shut down, while `gatsby-plugin-google-gtag` loads the gtag.js snippet that GA4 measurement ids use. It also accepts Google Ads and Marketing Platform ids in the same `trackingIds` list.

### Why does the build still work without an id?

The plugin entry is added to the array only when `GATSBY_GA_MEASUREMENT_ID` is set, so a fresh clone or a contributor's machine builds without analytics and without an error. The agent shows both builds in the pull request.

### Will I see pageviews in gatsby develop?

No. The plugin only loads in production builds. To check locally, run `gatsby build && gatsby serve` with the variable set, which is exactly what the agent did in the sandbox.

### What about Do Not Track and IP anonymisation?

`respectDNT: true` keeps the tag from loading for visitors with Do Not Track enabled, and `anonymize_ip: true` in `gtagConfig` asks Google to truncate the IP. Both are on in the pull request; a reviewer who needs different settings changes two lines in `gatsby-config.js`.

## More Gatsby jobs

- [Add Dark Mode to a Gatsby Blog](https://getrush.ai/run/add-dark-mode/gatsby/)
- [Add Draft Posts to a Gatsby Blog](https://getrush.ai/run/add-draft-posts/gatsby/)
- [Add Featured Images to a Gatsby Blog](https://getrush.ai/run/add-featured-images/gatsby/)

## The same job on other stacks

- [Add Analytics to an Astro Blog](https://getrush.ai/run/add-analytics/astro/)
- [Add Analytics to an Expo App](https://getrush.ai/run/add-analytics/expo/)

## More jobs like this: Hand off a long task

- [Add ansible-lint to CI for an Ansible Role](https://getrush.ai/run/add-ansible-lint/ansible/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
