Add Google Analytics to NextJs project.

nextjsgoogle analytics

Google Analytics lets you measure your advertising ROI as well as track your Flash, video, and social networking sites and applications. Adding Google Analytics to your next project is simple yet a little confusing. So in this blog, we will understand how to add Google Analytics to your next project with a simple and straightforward guide.

Firstly, we need to install a third-party library by using the command npm install @next/third-parties.  

Load Google Analytics for all routes:

To load Google Analytics for all routes, add the component directly in your root layout.js. Add import { GoogleAnalytics } from '@next/third-parties/google' and then use the component <GoogleAnalytics gaId="G-XYZ" />, replacing G-XYZ with your actual Google Analytics tag ID. After adding all this, the code will look something like this.

Load Google Analytics for single routes:

For single routes, navigate to your file, then add import { GoogleAnalytics } from '@next/third-parties/google' and use the component <GoogleAnalytics gaId="G-XYZ" /> at the top of your function. For example, I have added it in Home(). Check the snippet below for better understanding. That's how you can add Google Analytics inside your next project. Note to always add the GoogleAnalytics component inside a function which you are using and avoid creating a new function to add the GoogleAnalytics component. If you want to check this process from the official Next.js site, here is link.

© All right reserved by throughDev