16 visitors

Setting Up Google Tag Manager in a Next.js Application

2025-06-05

Next.jsGoogle AnalyticsTag ManagerTypeScript

Introduction

In this post, I'll share how I implemented Google Tag Manager in my Next.js portfolio website. The implementation includes real-time visitor tracking and a clean UI component to display visitor counts.

Setting Up Google Tag Manager

First, we need to set up Google Tag Manager and get the necessary credentials. Here's a step-by-step guide:

1. Create a Google Analytics 4 Property

  1. Go to Google Analytics
  2. Click "Start measuring" or "Create Property"
  3. Enter your property details (name, timezone, currency)
  4. Choose "Web" as your platform
  5. Enter your website URL and stream name
  6. Note down your Measurement ID (starts with "G-")

2. Set Up Google Tag Manager

  1. Go to Google Tag Manager
  2. Create a new account or select an existing one
  3. Set up a new container for your website
  4. Choose "Web" as your platform
  5. Note down your GTM Container ID (starts with "GTM-")

3. Install Required Package

Install the Next.js third-party package for Google Tag Manager:
npm install @next/third-parties
# or
yarn add @next/third-parties
# or
pnpm add @next/third-parties

4. Configure Environment Variables

Create a .env.local file in your project root and add the following variables:
# Google Tag Manager Configuration
NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID=GTM-XXXXXXXXXX  # Your GTM Container ID

5. Integration in Layout

Import and use the GoogleTagManager component from @next/third-parties/google in your root layout:
import { GoogleTagManager } from '@next/third-parties/google'

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head />
      <body className={cn("bg-background font-sans antialiased relative")}>
        <ThemeProvider
          attribute="class"
          defaultTheme="system"
          enableSystem
          disableTransitionOnChange
        >
          <NavBar />
          <main id="main" className="container">
            {children}
          </main>
        </ThemeProvider>
      </body>
      <GoogleTagManager gtmId={process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID!} />
    </html>
  );
}

Best Practices

When implementing Google Tag Manager in a Next.js application, consider these best practices:
  • Use environment variables for sensitive credentials
  • Implement proper error handling
  • Consider rate limiting and caching for API calls
  • Follow privacy regulations and add cookie consent if needed

Conclusion

Implementing Google Tag Manager in a Next.js application provides a powerful way to manage various tracking tags and analytics tools. Using the official @next/third-parties package ensures better integration and performance with Next.js applications.

References