Google Analytics can be integrated in a NextJS app by including the installation script in the root layout.js script and configuring the admin indicating a single page application.
1) Including Script in Root Layout
Include the installation script in the root layout.js script so that it will execute for all pages.
app/
|-- layout.js
layout.js should look something like this after integration. Replace the Google Analytics measurement id with your own.
import Script from 'next/script'
export default function RootLayout({ children }) {
return (
<html lang="en">
<head>
<Script
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"
/>
<Script>
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXX');
`}
</Script>
</head>
<body>
{children}
</body>
</html>
)
}
We are using NextJS' Script component which is the preferred way of loading scripts
2) Configuring Google Analytics
If we are using NextJS' Link component for page linking, NextJS behaves like a single page application. In this case Google Analytics needs to know it so that it can track analytics based on browser history events.
- Go to Google Analytics > Admin > Data collection and modification > Data streams > Web
Configure enhanced measurement
Go to Page Views > Show Advanced Settings and check the checkbox Page changes based on browser history events