Skip to main content

How to Add Google Analytics to Your Next.js Application

· 3 min read

Introduction

This article will walk you through the steps of integrating Google Analytics into your Next.js application and using the data to improve user experience.

Why Do You Need Google Analytics?

Google Analytics is a free service that collects data on users' interactions with your website. It provides insights on how people find your site, what they do when they get there and what they click on.

Google Analytics is one of the most popular analytics tools in the world. It is used by more than 175 million websites and has over 2 million active users.

The tool provides insights into how people use your website. It can help you understand their behaviour, which pages they are looking at, which links have been clicked and where they come from. You can also see which devices are being used to access your website, what operating system the visitors have and their location to name a few things that it tracks.

Why nextjs?

Next.js is an open-source framework for building web applications with JavaScript. It aims to be a minimalistic framework that makes it easy to create universal web applications that work well on both client and server side.

Installing next.js

npx create-next-app@latest
# or
yarn create next-app
# or
pnpm create next-app

If you want to start with a TypeScript project you can use the --typescript flag:

npx create-next-app@latest --typescript
# or
yarn create next-app --typescript
# or
pnpm create next-app --typescript

Setting up Google Tag Manager with Next.js application

Open your _app.js/ts file add the following at the top of your component.

...
<Script
strategy="lazyOnload"
src={'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX'}
/>

<Script strategy="lazyOnload" id="ga-script">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXX', {
page_path: window.location.pathname,
});
`}
</Script>
...
info

Make sure to replace G-XXXXXXX withyour Mesurment ID

Additional step

If you used next.config.js file for configurations then make sure to add the google tag manager link to the Allowed ContentSecurityPolicy at the script-src like bellow:

tip

script-src 'self' 'unsafe-eval' 'unsafe-inline' googletagmanager.com/gtag/js?id=G-XXXXXXX

See also

Conclusion

I hope this was helpful to you and You have a better understanding of the way to add google analytics to your nextjs projects.

Happy coding 🎉!