How to Setup Google Analytics

in Next.js

Saddam
September 23, 2024

Boost your website's performance insights by integrating Google Analytics with your Next.js project. This comprehensive guide walks you through the process, from setting up your Google Analytics account to implementing tracking in your Next.js application.

Step 1: Set up Google Analytics

Before we add Google Analytics to your Next.js project, you need to set up a Google Analytics account and create a property for your website. Here's how:

  1. Go to Google Analytics and sign in with your Google account.
  2. Click on the "Admin" button in the bottom left corner.
  3. In the Account column, click "Create Account" if you don't have one, or select an existing account.
  4. In the Property column, click "Create Property".
  5. Choose "Web" as the platform.
  6. Enter your website name and URL.
  7. Click "Create" to finalize the property creation.
  8. You'll be presented with a tracking ID that looks like "UA-XXXXXXXXX-X" (for Universal Analytics) or a Measurement ID that looks like "G-XXXXXXXXXX" (for Google Analytics 4). This is your GOOGLE_ANALYTICS_ID.

Step 2: Install next/script in your Next.js project

If you haven't already, make sure to install the next/script component:

npm install next

Step 3: Modify your layout.tsx file

Navigate to your app/layout.tsx file (or create one if it doesn't exist) and make the following changes:

  1. Import the Script component at the top of the file:
import Script from "next/script";
  1. Inside your layout component, add the Google Analytics script tags. Here's an example of how your layout.tsx might look:

  import Script from "next/script";

  export default function RootLayout({
    children,
  }: {
    children: React.ReactNode
  }) {
    return (
      <html lang="en">
        <head>
          <Script
            strategy="lazyOnload"
            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
          />
          <Script strategy="lazyOnload" id="google-analytics">
            {`
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
                page_path: window.location.pathname,
              });
            `}
          </Script>
        </head>

        <body>{children}</body>
      </html>
    );
  }
  

Make sure to adjust the content inside the body tag as per your code and requirements.

Step 4: Set up environment variables

To keep your Google Analytics ID secure and easily configurable, it's best to use environment variables:

  1. Create a .env.local file in the root of your project if it doesn't exist.
  2. Add your Google Analytics ID to this file:
NEXT_PUBLIC_GOOGLE_ANALYTICS=G-XXXXXXXXXX

Replace G-XXXXXXXXXX with your actual Google Analytics ID.

Step 5: Update .gitignore

Make sure your .env.local file is listed in your .gitignore to prevent your Google Analytics ID from being exposed in your repository.

Step 6: Test your implementation

  1. Run your Next.js application:
npm run dev
  1. Open your website in a browser and navigate to different pages.
  2. Go to your Google Analytics dashboard and check the "Real-Time" section to see if your visits are being tracked.

By following these steps, you should now have Google Analytics successfully integrated into your Next.js project!