Last active
November 30, 2022 19:05
-
-
Save crucialfelix/a2813a58e68b034bd28ea09163ffb5f0 to your computer and use it in GitHub Desktop.
Google Analytics for Next.js with next/router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* analytics.js; | |
* Copyright 2019 Chris Sattinger | |
* MIT license - do as thou wilt | |
* | |
* This will send page views on route change to Google Analytics. | |
* Works with https://nextjs.org/ and https://github.com/fridays/next-routes | |
**/ | |
import Router from "next/router"; | |
import ReactGA from "react-ga"; | |
/** | |
* Call this once in App (pages/_app.js) in componentDidMount | |
* | |
* componentDidMount() { | |
* initGA(process.env.UA); | |
* } | |
* | |
* Set UA environment variable to your "UA-000000-01" | |
* | |
* This attaches only if process.browser and UA is set. | |
* | |
* @param {string} UA Google Analytics UA code | |
*/ | |
export const initGA = UA => { | |
if (UA && process.browser) { | |
ReactGA.initialize(UA, { debug: !process.env.production }); | |
logPageViews(); | |
} | |
}; | |
export const logPageView = () => { | |
ReactGA.set({ page: window.location.pathname }); | |
ReactGA.pageview(window.location.pathname); | |
}; | |
export const logEvent = (category = "", action = "", label = "") => { | |
if (category && action) { | |
ReactGA.event({ category, action, label }); | |
} | |
}; | |
export const logException = (description = "", fatal = false) => { | |
if (description) { | |
ReactGA.exception({ description, fatal }); | |
} | |
}; | |
export function logPageViews() { | |
logPageView(); | |
Router.events.on("routeChangeComplete", () => { | |
logPageView(); | |
}); | |
} |
You could put this file anywhere outside of pages. utils services etc.
Import initGA in (pages/_app.js) and call it in componentDidMount:
componentDidMount() {
initGA(process.env.UA);
}
or if you are using a functional App component then useEffect
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How/Where is this analytics.js integrated in a React/Next application? That is the tricky part. Thanks !