Gathering detailed insights and metrics for bld-nextjs-google-analytics
Gathering detailed insights and metrics for bld-nextjs-google-analytics
Gathering detailed insights and metrics for bld-nextjs-google-analytics
Gathering detailed insights and metrics for bld-nextjs-google-analytics
npm install bld-nextjs-google-analytics
Typescript
Module System
TypeScript (99.24%)
JavaScript (0.76%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
550 Stars
998 Commits
48 Forks
3 Watchers
6 Branches
14 Contributors
Updated on Jul 05, 2025
Latest Version
0.0.23
Package Id
bld-nextjs-google-analytics@0.0.23
Unpacked Size
28.45 kB
Size
8.94 kB
File Count
38
Published on
Dec 06, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
21
1
⚠️ This is a fork of next-google-analytics. It has been modified to better support user_id and other GA features. ⚠️
Google Analytics for Next.js
This package optimizes script loading using Next.js Script
tag, which means that it will only work on apps using Next.js >= 11.0.0.
npm install --save nextjs-google-analytics
Add the GoogleAnalytics
component with the trackPageViews
prop set to true
to your custom App file:
1// pages/_app.js 2import { GoogleAnalytics } from "nextjs-google-analytics"; 3 4const App = ({ Component, pageProps }) => { 5 return ( 6 <> 7 <GoogleAnalytics trackPageViews /> 8 <Component {...pageProps} /> 9 </> 10 ); 11}; 12 13export default App;
You 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.
Your Google Analytics measurement id is read from NEXT_PUBLIC_GA_MEASUREMENT_ID
environment variable, so make sure it is set in your production environment:
If the variable is not set or is empty, nothing will be loaded, making it safe to work in development.
To load it and test it on development, add:
NEXT_PUBLIC_GA_MEASUREMENT_ID="G-XXXXXXXXXX"
to your .env.local
file.
As an alternative, you can use the gaMeasurementId
param to pass your Google Analytics measurement id.
The 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.
Use the GoogleAnalytics
component to load the gtag scripts. You can add it to a 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):
1// pages/_app.js 2import { GoogleAnalytics } from "nextjs-google-analytics"; 3 4const App = ({ Component, pageProps }) => { 5 return ( 6 <> 7 <GoogleAnalytics /> 8 <Component {...pageProps} /> 9 </> 10 ); 11}; 12 13export default App;
By default, scripts are loaded using the afterInteractive
strategy, which means they are injected on the client-side and will run after hydration.
If you need more control, the component exposes the strategy prop to control how the scripts are loaded:
1// pages/_app.js 2import { GoogleAnalytics } from "nextjs-google-analytics"; 3 4const App = ({ Component, pageProps }) => { 5 return ( 6 <> 7 <GoogleAnalytics strategy="lazyOnload" /> 8 <Component {...pageProps} /> 9 </> 10 ); 11}; 12 13export default App;
also, you can use alternative to default path for googletagmanager script by
1<GoogleAnalytics gtagUrl="/gtag.js" />
To track page views set the trackPageViews
prop of the GoogleAnalytics
component to true.
1// pages/_app.js 2import { GoogleAnalytics } from "nextjs-google-analytics"; 3 4const App = ({ Component, pageProps }) => { 5 return ( 6 <> 7 <GoogleAnalytics trackPageViews /> 8 <Component {...pageProps} /> 9 </> 10 ); 11}; 12 13export default App;
By 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:
1// pages/_app.js 2import { GoogleAnalytics } from "nextjs-google-analytics"; 3 4const App = ({ Component, pageProps }) => { 5 return ( 6 <> 7 <GoogleAnalytics trackPageViews={{ ignoreHashChange: true }} /> 8 <Component {...pageProps} /> 9 </> 10 ); 11}; 12 13export default App;
As an alternative, you can directly call the usePageViews
hook inside a custom App component, do not set trackPageViews
prop on the GoogleAnalytics
component or set it to false (default):
1// pages/_app.js 2import { GoogleAnalytics, usePageViews } from "nextjs-google-analytics"; 3 4const App = ({ Component, pageProps }) => { 5 usePageViews(); // IgnoreHashChange defaults to false 6 // usePageViews({ ignoreHashChange: true }); 7 8 return ( 9 <> 10 <GoogleAnalytics /> {/* or <GoogleAnalytics trackPageViews={false} /> */} 11 <Component {...pageProps} /> 12 </> 13 ); 14}; 15 16export default App;
The module also exports a pageView
function that you can use if you need more control.
You can use the event
function to track a custom event:
1import { useState } from "react"; 2import Page from "../components/Page"; 3import { event } from "nextjs-google-analytics"; 4 5export function Contact() { 6 const [message, setMessage] = useState(""); 7 8 const handleInput = (e) => { 9 setMessage(e.target.value); 10 }; 11 12 const handleSubmit = (e) => { 13 e.preventDefault(); 14 15 event("submit_form", { 16 category: "Contact", 17 label: message, 18 }); 19 20 setState(""); 21 }; 22 23 return ( 24 <Page> 25 <h1>This is the Contact page</h1> 26 <form onSubmit={handleSubmit}> 27 <label> 28 <span>Message:</span> 29 <textarea onChange={handleInput} value={message} /> 30 </label> 31 <button type="submit">submit</button> 32 </form> 33 </Page> 34 ); 35}
You can use the consent
function to update your users' cookie preferences (GDPR).
1 const consentValue: 'denied' | 'granted' = getUserCookiePreferenceFromLocalStorage(); // 'denied' or 'granted' 2 3 consent({ 4 arg: 'update', 5 params: { 6 ad_storage: consentValue, 7 analytics_storage: consentValue, 8 }, 9 });
To send Next.js web vitals to Google Analytics you can use a custom event on the reportWebVitals
function inside a custom App component:
1// pages/_app.js 2import { GoogleAnalytics, event } from "nextjs-google-analytics"; 3 4export function reportWebVitals({ id, name, label, value }) { 5 event(name, { 6 category: label === "web-vital" ? "Web Vitals" : "Next.js custom metric", 7 value: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers 8 label: id, // id unique to current page load 9 nonInteraction: true, // avoids affecting bounce rate. 10 }); 11} 12 13const App = ({ Component, pageProps }) => { 14 return ( 15 <> 16 <GoogleAnalytics /> 17 <Component {...pageProps} /> 18 </> 19 ); 20}; 21 22export default App;
If you are using TypeScript, you can import NextWebVitalsMetric
from next/app
:
1import type { NextWebVitalsMetric } from "next/app"; 2 3export function reportWebVitals(metric: NextWebVitalsMetric) { 4 // ... 5}
gaMeasurementId
paramAll exported components, hooks, and functions, accept an optional gaMeasurementId
param that can be used in case no environment variable is provided:
1// pages/_app.js 2import { GoogleAnalytics, event } from "nextjs-google-analytics"; 3import { gaMeasurementId } from "./lib/gtag"; 4 5export function reportWebVitals({ 6 id, 7 name, 8 label, 9 value, 10}: NextWebVitalsMetric) { 11 event( 12 name, 13 { 14 category: label === "web-vital" ? "Web Vitals" : "Next.js custom metric", 15 value: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers 16 label: id, // id unique to current page load 17 nonInteraction: true, // avoids affecting bounce rate. 18 }, 19 gaMeasurementId 20 ); 21} 22const App = ({ Component, pageProps }) => { 23 usePageViews({ gaMeasurementId }); 24 25 return ( 26 <> 27 <GoogleAnalytics gaMeasurementId={gaMeasurementId} /> 28 <Component {...pageProps} /> 29 </> 30 ); 31}; 32 33export default App;
Install the Google Analytics Debugger.
Turn it on by clicking its icon to the right of the address bar.
Open the Chrome Javascript console to see the messages.
On Windows and Linux, press Control-Shift-J.
On Mac, press Command-Option-J.
Refresh the page you are on.
The module is written in TypeScript and type definitions are included.
Contributions, issues and feature requests are welcome!
Give a ⭐️ if you like this project!
No vulnerabilities found.
No security vulnerabilities found.