google analytics nextjs
- Install the necessary packages:
npm install next react react-dom
npm install @react-analytics/react-analytics
- Set up Google Analytics:
- Create a new Google Analytics property.
Obtain the Tracking ID.
Create a new file
next.config.js
at the root of your Next.js project:
module.exports = {
env: {
GA_TRACKING_ID: 'your_tracking_id_here',
},
};
- Create a new file
lib/gtag.js
to handle Google Analytics integration:
export const GA_TRACKING_ID = process.env.GA_TRACKING_ID;
export const pageview = (url) => {
window.gtag('config', GA_TRACKING_ID, {
page_path: url,
});
};
export const event = ({ action, category, label, value }) => {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
});
};
- Integrate Google Analytics in your
_app.js
or_app.tsx
file:
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import * as gtag from '../lib/gtag';
function MyApp({ Component, pageProps }) {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url) => {
gtag.pageview(url);
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return <Component {...pageProps} />;
}
export default MyApp;
- Add the Google Analytics script to your custom
Head
component (if not using Next.js built-in Head):
import Head from 'next/head';
const CustomHead = () => (
<Head>
{/ Other head elements /}
<script async src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}`} />
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', '${process.env.GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
);
export default CustomHead;
Import and use your custom
Head
component in your pages or layout.Verify the Google Analytics setup by checking the real-time reporting in your Google Analytics dashboard.