Skip to content

Instantly share code, notes, and snippets.

@crucialfelix
Last active November 30, 2022 19:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crucialfelix/a2813a58e68b034bd28ea09163ffb5f0 to your computer and use it in GitHub Desktop.
Save crucialfelix/a2813a58e68b034bd28ea09163ffb5f0 to your computer and use it in GitHub Desktop.
Google Analytics for Next.js with next/router
/**
* 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();
});
}
@juannavas31
Copy link

How/Where is this analytics.js integrated in a React/Next application? That is the tricky part. Thanks !

@crucialfelix
Copy link
Author

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