How to Add Google Analytics to a Next.js Website or Web App
Google Analytics is a free service that provides insights into the behavior of people visiting your website. It tells you which pages get the most views, how long people stay on your site, where they come from, what devices they use, and more. This data can help you make informed decisions about your website design, content, marketing, and performance.
In this blog post, I will show you how to add Google Analytics to your Next.js website or web app using the Global site tag (gtag.js) and the Next.js Script component.
Prerequisites
To follow along with this tutorial, you will need:
- A Next.js website or web app. If you don’t have one, you can create one using create-next-app.
- A Google Analytics account. If you don’t have one, you can create one here.
Step 1: Get the Google Analytics Measurement ID
The first step is to get the Google Analytics Measurement ID for your website or web app. This is a unique identifier that tells Google Analytics which data stream to track.
To get the Measurement ID, follow these steps:
- Log in to your Google Analytics account and go to the Admin tab.
- Under the Property column, click on Create Property.
- Enter a name for your property and select Web as the platform.
- Click Next and enter your website or web app name and URL.
- Click Create and copy the Measurement ID that appears under Tagging instructions.
Step 2: Add the Google Analytics Script to Your Next.js App
The next step is to add the Google Analytics script to your Next.js app using the Script component from next/script. This component is an extension of the HTML script tag that allows you to include third-party scripts with different loading strategies.
The Script component has three loading strategies:
- beforeInteractive: The script is loaded before the page is interactive. Use this for scripts that need to run before the user can interact with the page, such as analytics scripts.
- afterInteractive: The script is loaded after the page is interactive. Use this for scripts that don’t need to run before the user can interact with the page, such as chat widgets or social media buttons.
- lazyOnload: The script is loaded when the page is visible or when the user scrolls near it. Use this for scripts that are not essential for the initial rendering of the page, such as ads or comments.
For Google Analytics, we will use the beforeInteractive strategy to ensure that we capture all page views and events as soon as possible.
To add the Script component, open the pages/_app.js file and import it at the top:
import Script from 'next/script'
Then, add two Script components inside the return statement of your App component:
return (
<>
{/* Global Site Tag (gtag.js) - Google Analytics */}
<Script
strategy="beforeInteractive"
src={`https://www.googletagmanager.com/gtag/jsid=${process.env.NEXT_PUBLIC_GA_ID}`}
/>
<Script
id="gtag-init"
strategy="beforeInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
<Component {...pageProps} />
</>
)
The first Script component loads the gtag.js script from Google Tag Manager using your Measurement ID as a query parameter. The second Script component initializes the gtag function and configures it with your Measurement ID and the current page path.
Note that we are using process.env.NEXT_PUBLIC_GA_ID to access our Measurement ID from an environment variable. This is a good practice to avoid exposing sensitive information in your code. To set up an environment variable in Next.js, create a .env.local file in your project root directory and add this line:
NEXT_PUBLIC_GA_ID=YOUR_MEASUREMENT_ID
Replace YOUR_MEASUREMENT_ID with your actual Measurement ID and save the file. Next.js will automatically load this variable in