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
- Go to Google Analytics
- Click "Start measuring" or "Create Property"
- Enter your property details (name, timezone, currency)
- Choose "Web" as your platform
- Enter your website URL and stream name
- Note down your Measurement ID (starts with "G-")
2. Set Up Google Tag Manager
- Go to Google Tag Manager
- Create a new account or select an existing one
- Set up a new container for your website
- Choose "Web" as your platform
- 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.