{"id":13998473,"url":"https://github.com/MauricioRobayo/nextjs-google-analytics","last_synced_at":"2025-07-23T06:31:52.127Z","repository":{"id":37086703,"uuid":"400217638","full_name":"MauricioRobayo/nextjs-google-analytics","owner":"MauricioRobayo","description":"Google Analytics for Next.js","archived":false,"fork":false,"pushed_at":"2024-11-19T10:59:09.000Z","size":3186,"stargazers_count":536,"open_issues_count":23,"forks_count":49,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-11-22T18:48:35.084Z","etag":null,"topics":["analytics","google-analytics","google-tag-manager","gtag","nextjs","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MauricioRobayo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","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":"2021-08-26T15:27:53.000Z","updated_at":"2024-11-15T09:52:18.000Z","dependencies_parsed_at":"2023-09-27T16:11:11.133Z","dependency_job_id":"baaf6908-6a2b-4640-8be3-2d29c385d60d","html_url":"https://github.com/MauricioRobayo/nextjs-google-analytics","commit_stats":{"total_commits":734,"total_committers":16,"mean_commits":45.875,"dds":"0.23024523160762944","last_synced_commit":"5660aa13464f666c0103d00fafe40d99bfa7c4da"},"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MauricioRobayo%2Fnextjs-google-analytics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MauricioRobayo%2Fnextjs-google-analytics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MauricioRobayo%2Fnextjs-google-analytics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MauricioRobayo%2Fnextjs-google-analytics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MauricioRobayo","download_url":"https://codeload.github.com/MauricioRobayo/nextjs-google-analytics/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227245178,"owners_count":17753239,"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":["analytics","google-analytics","google-tag-manager","gtag","nextjs","typescript"],"created_at":"2024-08-09T19:01:42.159Z","updated_at":"2024-11-30T00:31:39.216Z","avatar_url":"https://github.com/MauricioRobayo.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"\u003e [!NOTE]\n\u003e You might not need this package. Please check [Third Party Libraries](https://nextjs.org/docs/app/building-your-application/optimizing/third-party-libraries) first.\n\n# Nextjs Google Analytics\n\n[![npm version](https://badge.fury.io/js/nextjs-google-analytics.svg)](https://badge.fury.io/js/nextjs-google-analytics)\n[![codecov](https://codecov.io/gh/MauricioRobayo/nextjs-google-analytics/branch/main/graph/badge.svg?token=ywhhMAVgON)](https://codecov.io/gh/MauricioRobayo/nextjs-google-analytics)\n[![CodeFactor](https://www.codefactor.io/repository/github/mauriciorobayo/nextjs-google-analytics/badge)](https://www.codefactor.io/repository/github/mauriciorobayo/nextjs-google-analytics)\n\n**Google Analytics for Next.js**\n\nThis package optimizes script loading using [Next.js `Script` tag](https://nextjs.org/docs/basic-features/script), which means that it will **only work on apps using Next.js \u003e= 11.0.0**.\n\n## Installation\n\n```\nnpm install --save nextjs-google-analytics\n```\n\n## TL;DR\n\nAdd the `GoogleAnalytics` component with the `trackPageViews` prop set to `true` to your [custom App](https://nextjs.org/docs/advanced-features/custom-app) file:\n\n```js\n// pages/_app.js\nimport { GoogleAnalytics } from \"nextjs-google-analytics\";\n\nconst App = ({ Component, pageProps }) =\u003e {\n  return (\n    \u003c\u003e\n      \u003cGoogleAnalytics trackPageViews /\u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default App;\n```\n\nYou can pass your _Google Analytics measurement id_ by setting it on the `NEXT_PUBLIC_GA_MEASUREMENT_ID` environment variable or using the `gaMeasurementId` prop on the `GoogleAnalytics` component. **The environment variable will override the prop if both are set**.\n\n## Usage\n\nYour _Google Analytics measurement id_ is read from `NEXT_PUBLIC_GA_MEASUREMENT_ID` environment variable, so make sure it is set in your production environment:\n\n- [Vercel](https://vercel.com/docs/environment-variables)\n- [Netlify](https://www.netlify.com/blog/2020/12/10/environment-variables-in-next.js-and-netlify/)\n\nIf the variable is not set or is empty, nothing will be loaded, making it safe to work in development.\n\nTo load it and test it on development, add:\n\n```\nNEXT_PUBLIC_GA_MEASUREMENT_ID=\"G-XXXXXXXXXX\"\n```\n\nto your `.env.local` file.\n\nAs an alternative, you can use the `gaMeasurementId` param to pass your _Google Analytics measurement id_.\n\nThe `NEXT_PUBLIC_GA_MEASUREMENT_ID` environment variable will take precedence over the `gaMeasurementId` param, so if both are set with different values, the environment variable will override the param.\n\n## Scripts\n\nUse the `GoogleAnalytics` component to load the gtag scripts. You can add it to a [custom App](https://nextjs.org/docs/advanced-features/custom-app) component and this will take care of including the necessary scripts for every page (or you could add it on a per page basis if you need more control):\n\n```js\n// pages/_app.js\nimport { GoogleAnalytics } from \"nextjs-google-analytics\";\n\nconst App = ({ Component, pageProps }) =\u003e {\n  return (\n    \u003c\u003e\n      \u003cGoogleAnalytics /\u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default App;\n```\n\nBy default, scripts are loaded using the `afterInteractive` strategy, which means they are injected on the client-side and will run after hydration.\n\nIf you need more control, the component exposes the [strategy](https://nextjs.org/docs/basic-features/script) prop to control how the scripts are loaded:\n\n```js\n// pages/_app.js\nimport { GoogleAnalytics } from \"nextjs-google-analytics\";\n\nconst App = ({ Component, pageProps }) =\u003e {\n  return (\n    \u003c\u003e\n      \u003cGoogleAnalytics strategy=\"lazyOnload\" /\u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default App;\n```\nalso, you can use alternative to default path for googletagmanager script by\n```js\n\u003cGoogleAnalytics gtagUrl=\"/gtag.js\" /\u003e\n```\n\n## Page views\n\nTo track page views set the `trackPageViews` prop of the `GoogleAnalytics` component to true.\n\n```js\n// pages/_app.js\nimport { GoogleAnalytics } from \"nextjs-google-analytics\";\n\nconst App = ({ Component, pageProps }) =\u003e {\n  return (\n    \u003c\u003e\n      \u003cGoogleAnalytics trackPageViews /\u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default App;\n```\n\nBy default it will be trigger on hash changes if `trackPageViews` is enabled, but you can ignore hash changes by providing an object to the `trackPageViews` prop:\n\n```js\n// pages/_app.js\nimport { GoogleAnalytics } from \"nextjs-google-analytics\";\n\nconst App = ({ Component, pageProps }) =\u003e {\n  return (\n    \u003c\u003e\n      \u003cGoogleAnalytics trackPageViews={{ ignoreHashChange: true }} /\u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default App;\n```\n\nAs an alternative, you can directly call the `usePageViews` hook inside a [custom App](https://nextjs.org/docs/advanced-features/custom-app) component, **do not set `trackPageViews` prop on the `GoogleAnalytics` component** or set it to false (default):\n\n```js\n// pages/_app.js\nimport { GoogleAnalytics, usePageViews } from \"nextjs-google-analytics\";\n\nconst App = ({ Component, pageProps }) =\u003e {\n  usePageViews(); // IgnoreHashChange defaults to false\n  // usePageViews({ ignoreHashChange: true });\n\n  return (\n    \u003c\u003e\n      \u003cGoogleAnalytics /\u003e {/* or \u003cGoogleAnalytics trackPageViews={false} /\u003e */}\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default App;\n```\n\nThe module also exports a `pageView` function that you can use if you need more control.\n\n## Custom event\n\nYou can use the `event` function to track a custom event:\n\n```js\nimport { useState } from \"react\";\nimport Page from \"../components/Page\";\nimport { event } from \"nextjs-google-analytics\";\n\nexport function Contact() {\n  const [message, setMessage] = useState(\"\");\n\n  const handleInput = (e) =\u003e {\n    setMessage(e.target.value);\n  };\n\n  const handleSubmit = (e) =\u003e {\n    e.preventDefault();\n\n    event(\"submit_form\", {\n      category: \"Contact\",\n      label: message,\n    });\n\n    setState(\"\");\n  };\n\n  return (\n    \u003cPage\u003e\n      \u003ch1\u003eThis is the Contact page\u003c/h1\u003e\n      \u003cform onSubmit={handleSubmit}\u003e\n        \u003clabel\u003e\n          \u003cspan\u003eMessage:\u003c/span\u003e\n          \u003ctextarea onChange={handleInput} value={message} /\u003e\n        \u003c/label\u003e\n        \u003cbutton type=\"submit\"\u003esubmit\u003c/button\u003e\n      \u003c/form\u003e\n    \u003c/Page\u003e\n  );\n}\n```\n\nFor the possible parameters that can be specified in the `event`, please refer to the `event` command in the Google tag API reference.\n\n- [Google tag API reference - event](https://developers.google.com/tag-platform/gtagjs/reference#event)\n\n## Consent\n\nYou can use the `consent` function to update your users' cookie preferences (GDPR).\n\n```js\n const consentValue: 'denied' | 'granted' = getUserCookiePreferenceFromLocalStorage(); // 'denied' or 'granted'\n \n consent({\n    arg: 'update',\n    params: {\n      ad_storage: consentValue,\n      analytics_storage: consentValue,\n      ad_user_data: consentValue,\n      ad_personalization: consentValue\n    },\n });\n```\n\nFor the possible values that can be specified in `arg` and `params`, please refer to the `consent` command in the Google tag API reference.\n\n- [Google tag API reference - consent](https://developers.google.com/tag-platform/gtagjs/reference#consent)\n\n## Web Vitals\n\nTo send [Next.js web vitals](https://nextjs.org/docs/advanced-features/measuring-performance#sending-results-to-analytics) to Google Analytics you can use a custom event on the `reportWebVitals` function inside a [custom App](https://nextjs.org/docs/advanced-features/custom-app) component:\n\n```js\n// pages/_app.js\nimport { GoogleAnalytics, event } from \"nextjs-google-analytics\";\n\nexport function reportWebVitals({ id, name, label, value }) {\n  event(name, {\n    category: label === \"web-vital\" ? \"Web Vitals\" : \"Next.js custom metric\",\n    value: Math.round(name === \"CLS\" ? value * 1000 : value), // values must be integers\n    label: id, // id unique to current page load\n    nonInteraction: true, // avoids affecting bounce rate.\n  });\n}\n\nconst App = ({ Component, pageProps }) =\u003e {\n  return (\n    \u003c\u003e\n      \u003cGoogleAnalytics /\u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default App;\n```\n\nIf you are using TypeScript, you can import `NextWebVitalsMetric` from `next/app`:\n\n```ts\nimport type { NextWebVitalsMetric } from \"next/app\";\n\nexport function reportWebVitals(metric: NextWebVitalsMetric) {\n  // ...\n}\n```\n\n## Using the `gaMeasurementId` param\n\nAll exported components, hooks, and functions, accept an optional `gaMeasurementId` param that can be used in case no environment variable is provided:\n\n```js\n// pages/_app.js\nimport { GoogleAnalytics, event } from \"nextjs-google-analytics\";\nimport { gaMeasurementId } from \"./lib/gtag\";\n\nexport function reportWebVitals({\n  id,\n  name,\n  label,\n  value,\n}: NextWebVitalsMetric) {\n  event(\n    name,\n    {\n      category: label === \"web-vital\" ? \"Web Vitals\" : \"Next.js custom metric\",\n      value: Math.round(name === \"CLS\" ? value * 1000 : value), // values must be integers\n      label: id, // id unique to current page load\n      nonInteraction: true, // avoids affecting bounce rate.\n    },\n    gaMeasurementId\n  );\n}\nconst App = ({ Component, pageProps }) =\u003e {\n  usePageViews({ gaMeasurementId });\n\n  return (\n    \u003c\u003e\n      \u003cGoogleAnalytics gaMeasurementId={gaMeasurementId} /\u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default App;\n```\n\n## Debugging you Google Analytics\n\n1. Install the [Google Analytics Debugger](https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna).\n2. Turn it on by clicking its icon to the right of the address bar.\n3. Open the Chrome Javascript console to see the messages.\n\n   On Windows and Linux, press Control-Shift-J.\n\n   On Mac, press Command-Option-J.\n\n4. Refresh the page you are on.\n\n## TypeScript\n\nThe module is written in TypeScript and type definitions are included.\n\n## Contributing\n\nContributions, issues and feature requests are welcome!\n\n## Show your support\n\nGive a ⭐️ if you like this project!\n\n## LICENSE\n\n[MIT](./LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMauricioRobayo%2Fnextjs-google-analytics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FMauricioRobayo%2Fnextjs-google-analytics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMauricioRobayo%2Fnextjs-google-analytics/lists"}