{"id":21974750,"url":"https://github.com/andrewrporter/nextjs-google-analytics-tutorial","last_synced_at":"2025-07-01T09:31:45.473Z","repository":{"id":141138354,"uuid":"485097907","full_name":"AndrewRPorter/nextjs-google-analytics-tutorial","owner":"AndrewRPorter","description":"Tutorial showing how to add Google Analytics to a Next.js application","archived":false,"fork":false,"pushed_at":"2022-04-24T18:23:38.000Z","size":47,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-22T23:41:38.607Z","etag":null,"topics":["example","google-analytics","nextjs","tracking","tutorial"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AndrewRPorter.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-04-24T17:45:51.000Z","updated_at":"2023-08-17T05:48:08.000Z","dependencies_parsed_at":"2024-08-17T21:01:43.812Z","dependency_job_id":null,"html_url":"https://github.com/AndrewRPorter/nextjs-google-analytics-tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/AndrewRPorter/nextjs-google-analytics-tutorial","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AndrewRPorter%2Fnextjs-google-analytics-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AndrewRPorter%2Fnextjs-google-analytics-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AndrewRPorter%2Fnextjs-google-analytics-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AndrewRPorter%2Fnextjs-google-analytics-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AndrewRPorter","download_url":"https://codeload.github.com/AndrewRPorter/nextjs-google-analytics-tutorial/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AndrewRPorter%2Fnextjs-google-analytics-tutorial/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262935813,"owners_count":23387259,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["example","google-analytics","nextjs","tracking","tutorial"],"created_at":"2024-11-29T15:47:42.313Z","updated_at":"2025-07-01T09:31:45.404Z","avatar_url":"https://github.com/AndrewRPorter.png","language":"JavaScript","readme":"# Next.js Google Analytics Setup\n\nBasic tutorial showing you how to utilize Google Analytics in Next.js.\n\n## Steps\n\n### 1. Create a Google Analytics account and setup a datastream\n\nGo to https://analytics.google.com/analytics/web and create an account/property for your application.\n\nAfter your account is created, should have a web property and a web steam created with a measurement ID. This measurement ID should be of the form: `G-XXXXXXXXX`. We will want to add this to a `.env` file. Create a new `.env.local` file at the base of your project and add the following value: `NEXT_PUBLIC_GOOGLE_ANALYTICS=G-XXXXXXXXX`. `XXXXXXXXX` should be the copied value from Google Analytics.\n\n### 2. Add gtag.js to our site\n\nThis is the google tagging framework that allows us to send event data to Google Analytics. [This guide](https://developers.google.com/analytics/devguides/collection/gtagjs) by google shows us how to install the gtag on our site. We will have to do things a little different to support this on Next.js.\n\nIf you don't already have a `_document.js` file created in your Next.js project, create one in `pages`. This allows us to set custom `\u003chead\u003e` elements, which is where our gtag script will live.\n\nAn example `_document.js` looks like this. Notice the scripts inside the Head tag. This is what initializes google analytics in our application.\n\n```js\nimport Document, { Html, Head, Main, NextScript } from \"next/document\";\n\nclass MyDocument extends Document {\n  render() {\n    return (\n      \u003cHtml\u003e\n        \u003cHead\u003e\n          \u003cscript\n            async\n            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}\n          /\u003e\n          \u003cscript\n            dangerouslySetInnerHTML={{\n              __html: `\n    window.dataLayer = window.dataLayer || [];\n    function gtag(){dataLayer.push(arguments);}\n    gtag('js', new Date());\n    gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {\n        page_path: window.location.pathname,\n    });\n    `,\n            }}\n          /\u003e\n        \u003c/Head\u003e\n        \u003cbody\u003e\n          \u003cMain /\u003e\n          \u003cNextScript /\u003e\n        \u003c/body\u003e\n      \u003c/Html\u003e\n    );\n  }\n}\n\nexport default MyDocument;\n```\n\n### 3. Setup a helper package to communicate with gtag\n\nCreate a new folder called `lib`. Within `lib`, create a new file called `ga.js`. This fill will help us communicate with the gtag in the window.\n\n`ga.js` will have to functions, one to track page views and one to track events.\n\n```js\nexport const pageview = (url) =\u003e {\n  if (window !== undefined) {\n    window.gtag(\"config\", process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {\n      page_path: url,\n    });\n  }\n};\n\nexport const event = ({ action, params }) =\u003e {\n  if (window !== undefined) {\n    window.gtag(\"event\", action, params);\n  }\n};\n```\n\n### 4. Add pageview tracking\n\nWithin our `_app.js` file, we are going to use the Next.js router to listen for event changes. If the event `routeChangeComplete` is triggered, we will send a pageview event. Read more about the custom App component in Next.js [here](https://nextjs.org/docs/advanced-features/custom-app).\n\nWe want to create a use effect hook in our app component that looks like:\n\n```js\nimport { useEffect } from \"react\";\nimport { useRouter } from \"next/router\";\nimport { pageview } from \"../lib/ga\";\n\n...\n\nconst router = useRouter();\n\n  useEffect(() =\u003e {\n    const handleRouteChange = (url) =\u003e {\n      pageview(url);\n    };\n\n    //When the component is mounted, subscribe to router changes\n    //and log those page views\n    router.events.on(\"routeChangeComplete\", handleRouteChange);\n\n    // If the component is unmounted, unsubscribe\n    // from the event with the `off` method\n    return () =\u003e {\n      router.events.off(\"routeChangeComplete\", handleRouteChange);\n    };\n  }, [router.events]);\n```\n\n_Note that this function will only work with Next.js `\u003cLink\u003e` component links. Regular `\u003ca\u003e` tags will not be execute the custom script we created. Instead, the gtag will be loaded into the head and a request will be sent off for a new page load._\n\n### 5. Event tracking\n\nSay for example you wanted to track a button click that submited a search field. You can use the `event` method we created in `lib/ga.js`.\n\nAfter importing the `event` function we can trigger an event on a button like so:\n\n```js\n\u003cbutton\n  onClick={() =\u003e\n    event({\n      action: \"search\",\n      params: {\n        search_term: \"test\",\n      },\n    })\n  }\n\u003e\n  Click me\n\u003c/button\u003e\n```\n\n### 6. (Optional) Ignoring in automated test suites\n\nIf you use automated testing frameworks like Cypress to test your applications, you will probably also want to ignore sending google analytics metrics for these tests.\n\nIn Cypress, you can do this by adding `\"*.google-analytics.com` to `blockHosts`.\n\n```\n\"blockHosts\": \"*.google-analytics.com\"\n```\n\nRead more about `blockHosts` in Cypress [here](https://docs.cypress.io/guides/references/configuration#Browser).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrewrporter%2Fnextjs-google-analytics-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandrewrporter%2Fnextjs-google-analytics-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrewrporter%2Fnextjs-google-analytics-tutorial/lists"}