Skip to content

Instantly share code, notes, and snippets.

@xtools-at
Last active August 10, 2022 14:56
Show Gist options
  • Save xtools-at/55ef2669051221241e05c76fdf8b738b to your computer and use it in GitHub Desktop.
Save xtools-at/55ef2669051221241e05c76fdf8b738b to your computer and use it in GitHub Desktop.
Google Analytics in Next.js - Examples using "react-ga"
// Google Analytics helper for Next.js
const ReactGA = require('react-ga');
module.exports = {
initGA: () => {
ReactGA.initialize('UA-XXXXXXX-NN');
},
logPageView: () => {
const page = window.location.pathname + window.location.search;
ReactGA.set({
page,
anonymizeIp: true,
});
ReactGA.pageview(page);
},
logEvent: (category = '', action = '', label = '', value = '', customDimensions = null, nonInteraction = false) => {
if (category && action && action !== 'generalError') {
let settings = {
anonymizeIp: true,
};
const data = { category, action };
if (label) data.label = label;
if (value) data.value = value;
if (nonInteraction) data.nonInteraction = true;
if (customDimensions) {
settings = {
...settings,
...customDimensions,
};
}
ReactGA.set(settings);
ReactGA.event(data);
}
},
logException: (description = '', fatal = false) => {
if (description) {
ReactGA.set({
anonymizeIp: true,
});
ReactGA.exception({ description, fatal });
}
},
logOutboundLink: (label = '') => {
if (label) {
ReactGA.set({
anonymizeIp: true,
});
ReactGA.outboundLink({ label });
}
},
logPurchase: (id = '', revenue = '') => {
if (id && revenue) {
ReactGA.plugin.execute('ec', 'setAction', 'purchase', {
id, revenue,
});
}
},
};
// ----------------------------------------------------
// in _app.js > App
useEffect(() => {
initGA()
// `routeChangeComplete` won't run for the first page load unless the query string is
// hydrated later on, so here we log a page view if this is the first render and
// there's no query string
if (!router.asPath.includes('?')) {
logPageView()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
// Listen for page changes after a navigation or when the query changes
router.events.on('routeChangeComplete', logPageView)
return () => {
router.events.off('routeChangeComplete', logPageView)
}
}, [router.events])
// ----------------------------------------------------
// Example for outbound link tracking via ExternalLink component
export const ExternalLink = (props) => {
const {className, href, sameWindow, noFollow, title, children, role} = props;
return (
<a className={`${className || ''}`}
href={href}
target={sameWindow ? '_self' : '_blank'}
rel={noFollow ? 'nofollow noopener' : 'noopener'}
title={title || ''}
role={role || 'link'}
onClick={() => logOutboundLink(href)}
>
{children}
</a>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment