Design Converter
Education
Developer Advocate
Last updated on Jun 3, 2024
Last updated on May 30, 2024
In today’s digital landscape, understanding user behavior and optimizing site performance are more critical than ever.
Integrating Google Analytics with your Next.js project can provide you with the insights needed to make data-driven decisions.
This blog will walk you through the essential steps to set up Google Analytics in a Next.js project, starting with account creation and configuration, moving through adding analytics scripts and culminating in advanced configurations like using Google Tag Manager and tracking custom events.
Whether you’re new to Next.js or looking to enhance your analytics capabilities, this guide is designed to help you add Google Analytics to your website, harness the full power of Google Analytics to improve user experience, and boost your website’s performance.
To start using Google Analytics with your Next.js project, you’ll first need to go through the google analytics account setup. Follow these steps for a smooth setup:
Sign Up for Google Analytics: Visit the Google Analytics homepage and sign in with your Google account. If you don’t have a Google account, create one.
Create a New Account: Click on the “Start measuring” button to begin the setup process. You’ll be prompted to enter an account name. This can be your business or personal name.
Set Up Your Property: After creating an account, you’ll need to set up a property. This involves entering a property name (e.g., “My Website”), selecting your reporting time zone, and choosing your currency. Properties in Google Analytics represent your website or app, and you can track multiple properties under one account.
Generate a Measurement ID: Once the property is created, you’ll be provided with a Measurement ID. This ID is essential for tracking data from your site and integrating it into Google Analytics.
After setting up your Google Analytics account, the next step is to configure a property. Here’s how to do it:
Configuring Data Streams: In the property setup, you'll need to create data streams. A data stream represents the source of data, such as your website. To do this, navigate to the "Data Streams" section under your property settings, click "Add Stream," and choose "Web" for website tracking.
<script>
tag.1import { useEffect } from 'react'; 2import Script from 'next/script'; 3 4function MyApp({ Component, pageProps }) { 5 useEffect(() => { 6 window.dataLayer = window.dataLayer || []; 7 function gtag(){dataLayer.push(arguments);} 8 gtag('js', new Date()); 9 gtag('config', 'YOUR_MEASUREMENT_ID'); 10 }, []); 11 12 return ( 13 <> 14 <Script 15 src="https://www.googletagmanager.com/gtag/js?id=YOUR_MEASUREMENT_ID" 16 strategy="afterInteractive" 17 /> 18 <Component {...pageProps} /> 19 </> 20 ); 21} 22 23export default MyApp;
Understanding the Google Analytics Dashboard: Once your data stream is configured and the script is added to your website, you can start seeing data in the Google Analytics dashboard. The dashboard provides comprehensive insights into user interactions, traffic sources, and other key metrics that help you understand your website's performance.
Navigating the Dashboard: Familiarize yourself with the various sections of the dashboard such as Realtime, Audience, Acquisition, Behavior, and Conversions. Each section offers detailed reports that are crucial for analyzing different aspects of your website traffic.
Enhanced Measurement: Google Analytics 4 (GA4) offers enhanced measurement features that automatically track certain user interactions like page views, scrolls, outbound clicks, and video engagements without additional code. Ensure these settings are enabled for more comprehensive data collection.
To start with Google Analytics in your Next.js project, you’ll first need to create a new Next.js project if you don’t already have one. Here’s how you can do it:
1npx create-next-app@latest my-nextjs-google-analytics 2cd my-nextjs-google-analytics
1npm install next
To keep your Google Analytics Measurement ID secure and easily configurable, you should store it in an environment file. Here's how you can do that:
1NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX
In your _app.js file, you'll import the Script component and use your environment variable to set up Google Analytics. Here’s an example of how to do it:
1import { useEffect } from 'react'; 2import Script from 'next/script'; 3import '../styles/globals.css'; 4 5function MyApp({ Component, pageProps }) { 6 useEffect(() => { 7 window.dataLayer = window.dataLayer || []; 8 function gtag() { 9 dataLayer.push(arguments); 10 } 11 gtag('js', new Date()); 12 gtag('config', process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID); 13 }, []); 14 15 return ( 16 <> 17 <Script 18 src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}`} 19 strategy="afterInteractive" 20 /> 21 <Script id="google-analytics" strategy="afterInteractive"> 22 {` 23 window.dataLayer = window.dataLayer || []; 24 function gtag(){dataLayer.push(arguments);} 25 gtag('js', new Date()); 26 gtag('config', '${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}'); 27 `} 28 </Script> 29 <Component {...pageProps} /> 30 </> 31 ); 32} 33 34export default MyApp;
This setup ensures that your Google Analytics tracking code is loaded asynchronously, improving your website’s performance. By using the NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable, you keep your Measurement ID secure and easily changeable without modifying your code.
To integrate Google Analytics into your Next.js project, you first need to add the Google Analytics script to your app.js file. This file is the entry point for all your pages, making it the ideal place to include global scripts. Open the app.js file in your Next.js project and import the next/script component. This component allows you to add third-party scripts to your application in an optimized way.
1import { useEffect } from 'react'; 2import Script from 'next/script'; 3import '../styles/globals.css'; 4 5function MyApp({ Component, pageProps }) { 6 useEffect(() => { 7 window.dataLayer = window.dataLayer || []; 8 function gtag() { 9 dataLayer.push(arguments); 10 } 11 gtag('js', new Date()); 12 gtag('config', process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID); 13 }, []); 14 15 return ( 16 <> 17 <Script 18 src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}`} 19 strategy="afterInteractive" 20 /> 21 <Script id="google-analytics" strategy="afterInteractive"> 22 {` 23 window.dataLayer = window.dataLayer || []; 24 function gtag(){dataLayer.push(arguments);} 25 gtag('js', new Date()); 26 gtag('config', '${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}'); 27 `} 28 </Script> 29 <Component {...pageProps} /> 30 </> 31 ); 32} 33 34export default MyApp;
The next/script component ensures that your script is loaded asynchronously by default. The strategy="afterInteractive" attribute indicates that the script should load after the page becomes interactive, which helps with the performance of your site.
To keep your code clean and modular, it's a good practice to create a separate component for Google Analytics. This component can handle the script loading and initialization.
1import { useEffect } from 'react'; 2import Script from 'next/script'; 3 4const GoogleAnalytics = () => { 5 useEffect(() => { 6 window.dataLayer = window.dataLayer || []; 7 function gtag() { 8 dataLayer.push(arguments); 9 } 10 gtag('js', new Date()); 11 gtag('config', process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID); 12 }, []); 13 14 return ( 15 <> 16 <Script 17 src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}`} 18 strategy="afterInteractive" 19 /> 20 <Script id="google-analytics" strategy="afterInteractive"> 21 {` 22 window.dataLayer = window.dataLayer || []; 23 function gtag(){dataLayer.push(arguments);} 24 gtag('js', new Date()); 25 gtag('config', '${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}'); 26 `} 27 </Script> 28 </> 29 ); 30}; 31 32export default GoogleAnalytics;
Now that you have created the GoogleAnalytics component, you need to integrate it into your _app.js file.
1import GoogleAnalytics from '../components/GoogleAnalytics'; 2import '../styles/globals.css'; 3 4function MyApp({ Component, pageProps }) { 5 return ( 6 <> 7 <GoogleAnalytics /> 8 <Component {...pageProps} /> 9 </> 10 ); 11} 12 13export default MyApp;
With these steps, you effectively modularize your Google Analytics implementation, making your Next.js project easier to maintain and extend. This setup ensures that your Google Analytics script is correctly loaded and initialized, allowing you to track user interactions and gather valuable insights from your website.
Google Tag Manager (GTM) is a powerful tool that simplifies the process of managing and deploying marketing tags on your website. Here's how to set it up and integrate it with Google Analytics:
Create a Google Tag Manager Account: Visit the Google Tag Manager homepage and sign in with your Google account. Click on "Create Account" and follow the prompts to set up a new account and container. The container represents your website or app.
Install the GTM Snippet: After creating the container, you'll receive two snippets of code. One goes in the <head>
section and the other in the <body>
section of your HTML. In a Next.js project, you can add these snippets in the _document.js file.
1// pages/_document.js 2import { Html, Head, Main, NextScript } from 'next/document'; 3 4export default function Document() { 5 return ( 6 <Html> 7 <Head> 8 {/* Google Tag Manager */} 9 <script dangerouslySetInnerHTML={{ 10 __html: ` 11 (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': 12 new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], 13 j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 14 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); 15 })(window,document,'script','dataLayer','GTM-XXXXXX'); 16 ` 17 }} /> 18 {/* End Google Tag Manager */} 19 </Head> 20 <body> 21 <Main /> 22 <NextScript /> 23 {/* Google Tag Manager (noscript) */} 24 <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX" 25 height="0" width="0" style={{display:'none',visibility:'hidden'}}></iframe></noscript> 26 {/* End Google Tag Manager (noscript) */} 27 </body> 28 </Html> 29 ); 30}
Set Up a Google Analytics Tag in GTM: After installing the GTM snippet, you need to create a Google Analytics tag within GTM. Go to your GTM dashboard, click on "Tags" and then "New". Select "Google Analytics: GA4 Configuration" and enter your Measurement ID.
Publish the Container: After setting up the tag, click on "Submit" and then "Publish" to make the changes live on your website. This will start sending data to your Google Analytics account.
Custom events allow you to track specific user interactions on your website. Here’s how to set up custom events using Google Tag Manager:
Create a Custom Event Trigger in GTM: In your GTM dashboard, go to "Triggers" and click "New". Choose "Custom Event" as the trigger type. Name your event (e.g., button_click) and define the event conditions.
Link the Trigger to a Tag: Create a new tag for the custom event. Choose "Google Analytics: GA4 Event" and link it to the custom event trigger you created. Configure the event parameters as needed.
1import { useEffect } from 'react'; 2 3const handleClick = () => { 4 window.gtag('event', 'button_click', { 5 event_category: 'button', 6 event_label: 'cta_button', 7 }); 8}; 9 10function MyComponent() { 11 useEffect(() => { 12 window.dataLayer = window.dataLayer || []; 13 function gtag() { 14 dataLayer.push(arguments); 15 } 16 gtag('js', new Date()); 17 gtag('config', process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID); 18 }, []); 19 20 return <button onClick={handleClick}>Click Me</button>; 21} 22 23export default MyComponent;
Track Page Views Automatically: Google Analytics 4 tracks page views automatically. Ensure that your GA4 configuration tag is set up correctly in GTM.
Track Other User Interactions: For interactions like form submissions, video plays, or other actions, you can create additional custom event triggers in GTM. Define the event parameters and link them to your Google Analytics configuration.
Using Google Tag Manager and custom events, you can gain deeper insights into how users interact with your website, enabling you to make data-driven decisions to improve user experience and optimize your site's performance.
Integrating Google Analytics with your Next.js project is a powerful way to gain insights into your users' behavior and website performance. With the steps outlined in this guide, you can set up Google Analytics, track page views, monitor user interactions, and leverage Google Tag Manager for advanced tracking capabilities.
Always store sensitive information like your Measurement ID in environment variables and consider creating a dedicated component for Google Analytics to keep your codebase clean. With these analytics tools, you're well-equipped to make informed decisions that can lead to better user experiences and improved website outcomes.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.