Quickly adding Google Analytics to Next.js with FAQs
This article not only demonstrates how to add Google Analytics to a Next.js app but also explains what you're actually doing.

Search for a command to run...
This article not only demonstrates how to add Google Analytics to a Next.js app but also explains what you're actually doing.

No comments yet. Be the first to comment.
Do you ever watch your view count rise and wonder which posts are being read the most? I know I did. That is one reason why I chose to develop my own Dev.to analytics dashboard to display historical data such as view, reaction and follower increase ...

Ever wondered if you can share interfaces, types and functions between TypeScript projects? I'm currently developing a project consisting of two separate TypeScript applications, one being a React.js dashboard and the other an Azure Function app writ...

My personal website is built on Next.js and uses both the getStaticProps and getStaticPaths functions to dynamically generate the /blog/ and /portfolio/ pages at build time. While updating both methods to use their proper TypeScript types, following ...

Usually, when adding icons to a website, I'll use React-icons. There are times, however, when I prefer to copy an exact SVG from a website. Downloading an SVG isn't as easy as downloading an image on a website. Fortunately, SVG Export extracted them ...

The final weekend of January 2021 was uneventful in comparison with other years - in the UK we were in full lockdown due to the Coronavirus. It was, however, the perfect opportunity to completely rewrite my personal website. Why? I decided to redesig...

I use Google Analytics to track how many users are visiting websites that I develop on a weekly basis, how long they stay on the site and what are the most popular pages.
It's easy to add to your site and in minutes you'll go from having no clue how people are using your website to being able to record and analyse every detail on every interaction a user has with your website.
I'll split this post up into 3 parts:
_document.js file and what does it do? or how to I get a GA_MEASUREMENT_ID?Key takeaway if you're glancing at this article:
Adding Google Analytics to a Next.js project is easy and you can copy and paste the code below. I wouldn't use an external NPM module as you're just adding another dependency that can become outdated in the future.
Google Analytics is a web analytics service offered by Google that tracks and reports website traffic.
I've recently begun adding Google Analytics to every website that I've developed including wallisconsultancy.co.uk which I recently developed alongside a series of tutorial blog posts. Google Analytics is great at tracking website usage and more, although I currently use it purely to monitor user count, most popular pages and page performance which is all reported on the Google Analytics dashboard.
A Google Analytics dashboard
In addition to the above, it's free and takes minutes to set up with a Next.js project (if you follow this post ๐).
GA_MEASUREMENT_ID) that is given to you and is used to identify your website with Google. Keep the GA_MEASUREMENT_ID handy, you'll need it. - I've covered this in the FAQs if you haven't used Google Analytics before._document.js file in your Next.js projectCreate a custom _document.js file in your pages directory and add the following code:
If you're using TypeScript, check out this custom _document.tsx on GitHub instead.
import Document, {
Html, Head, Main, NextScript,
} from 'next/document';
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
const GA_MEASUREMENT_ID = 'GA_MEASUREMENT_ID'; // Paste your GTAG here
return (
<Html lang="en">
<Head>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
/>
<script
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_MEASUREMENT_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
If you've already got a custom _document.js then the key parts are within the Head component (remember to add the GA_MEASUREMENT_ID variable):
<Head>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
/>
<script
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_MEASUREMENT_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
Explanation:
script tag the Google Analytics JavaScript file is loaded into the browser.script tag the Google Analytics code is initialised and tracking is started on the current page.Once you've added your GA_MEASUREMENT_ID and pushed your changes into a live environment such as Vercel, you should see data appearing on your Google Analytics dashboard - if you don't, try visiting your website!
And that is all it takes to add Google Analytics to your Next.js application - told you it was easy!
The gtag.js is a script which allows you to send event data to Google, in this case it's used for Google Analytics. Read more about it and the GA_MEASUREMENT_ID at Google Developers - gtag.js.
GA_MEASUREMENT_ID and how do I get one?The GA_MEASUREMENT_ID is the ID of the Google Analytics property that you want to collect data for. To get a GA_MEASUREMENT_ID you need to create a new property on Google Analytics - you can follow this Google Support article to learn how to sign up to Google Analytics and create a property.
_document.js and _app.js files in a Next.js project?The Next.js specific _document.js and _app.js are two special files that live in the pages directory but are not rendered as pages by Next.js (you can't reach /_document in your browser).
Note: The Head component used in _document.js's Head different to next/head and should be used for common code on every page.
_document.js is rendered server-side only and controls the <html> and <body> tags of HTML. It can be used to add custom elements into your <html> tag that will be the same on every page such as the Google Analytics code or a favicon.
_app.js is rendered client-side, potentially on every page change. It's essentially a wrapper around each Next.js page that you have. It can be used to maintain a consistent layout on each page, add a custom CSS stylesheet or persist state on a page change.
You can read more about these on the Next.js website:
_document.js file over _app.js?The Head component (from next/document) that is used in _document.js is rendered serverside whereas the Head component (from next/head) in _app.js will update on each page change meaning that the Google Analytics script may be reloaded which could slow down the site.
If anything I've said has helped you add Google Analytics to your site, give me a reaction.
Any more questions? Let me know in the comments!
Thanks for reading the article!