Google Analytics
Integrate Google Analytics using Next.js Third Parties library.
StarterKitPro 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:
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:
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:
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:
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:
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:
- Go to your Google Analytics 4 property.
- Navigate to Admin (gear icon, bottom left).
- In the Property column, click on Data Streams.
- Select the relevant web data stream.
- Your Measurement ID is displayed in the top right.