LogoStarterkitpro
Features/Analytics

Google Analytics

Integrate Google Analytics using Next.js Third Parties library.

StarterKit Pro simplifies integrating Google Analytics into your Next.js application using the built-in @next/third-parties library. This provides an optimized way to load the Google Analytics script.

Optional Feature

Google Analytics isn’t included by default to keep the core lean. Install it if you need to track analytics or custom events to monitor user behavior.

Installation

First, ensure you have the necessary package installed. While @next/third-parties is often included with newer Next.js versions, you can explicitly install it if needed:

Terminal
npm install @next/third-parties

Basic Setup

To enable Google Analytics tracking across your entire application, import the GoogleAnalytics component and add it to your root layout file (app/layout.tsx).

You'll need your Google Analytics Measurement ID, which should be stored as an environment variable.

Add Environment Variable

Create or update your .env.local file with your Measurement ID:

NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX

Replace G-XXXXXXXXXX with your actual ID.

Important

Prefixing the variable with NEXT_PUBLIC_ makes it available in the browser environment, which is necessary for client-side analytics.

Update Root Layout

Import and include the GoogleAnalytics component in src/app/layout.tsx:

app/layout.tsx
import { GoogleAnalytics } from "@next/third-parties/google";
// ... other imports
 
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body>{children}</body>
      // ... other components
      {process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID && (
        <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID} />
      )}
      // ... other components
    </html>
  );
}

With this setup, page views will be automatically tracked by Google Analytics.

Tracking Custom Events

Beyond automatic page views, you might want to track specific user interactions, such as button clicks or form submissions. The @next/third-parties library provides the sendGAEvent function for this.

Import sendGAEvent

Import the function into the component where you want to track the event:

import { sendGAEvent } from "@next/third-parties/google";

Call sendGAEvent on Interaction

Trigger the function within an event handler, like onClick. You can pass custom data relevant to the event. For example, tracking a click on a "Purchase" button for a specific product variant:

components/shared/purchase-button.tsx
"use client";
 
import { sendGAEvent } from "@next/third-parties/google";
// ... rest of your imports
 
export const PurchaseButton = ({ variantId }: { variantId: string }) => {
  const handleClick = () => {
    // ... rest of your purchase logic
 
    // Send custom event to Google Analytics
    sendGAEvent("event", "purchase_click", {
      // pass any custom parameters you need for filteration later in Google Analytics
      variant_id: variantId,
    });
 
    // ... rest of your purchase logic
  };
 
  return <Button onClick={handleClick}>Purchase Now</Button>;
};

The first argument to sendGAEvent can be "event" for standard events or "exception" for tracking errors. The second argument is the event name (e.g., purchase_click, add_to_cart). The third argument is an optional object containing custom parameters. Ensure you use standard Google Analytics event parameters or register your custom dimensions/metrics in the GA interface.

Getting Your Measurement ID

You can find your Google Analytics Measurement ID (which starts with G-) in your Google Analytics account:

  1. Go to your Google Analytics 4 property.
  2. Navigate to Admin (gear icon, bottom left).
  3. In the Property column, click on Data Streams.
  4. Select the relevant web data stream.
  5. Your Measurement ID is displayed in the top right.

On this page