Setting Up Google Tag Manager in a Next.js Application
June 5, 2025
~2 min read
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:
bash
1npm install @next/third-parties
2# or
3yarn add @next/third-parties
4# or
5pnpm add @next/third-parties
4. Configure Environment Variables
Create a .env.local file in your project root and add the following variables:
bash
1# Google Tag Manager Configuration
2NEXT_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:
tsx
1import { GoogleTagManager } from '@next/third-parties/google'
2
3export default function RootLayout({
4 children,
5}: Readonly<{
6 children: React.ReactNode;
7}>) {
8 return (
9 <html lang="en" suppressHydrationWarning>
10 <head />
11 <body className={cn("bg-background font-sans antialiased relative")}>
12 <ThemeProvider
13 attribute="class"
14 defaultTheme="system"
15 enableSystem
16 disableTransitionOnChange
17 >
18 <NavBar />
19 <main id="main" className="container">
20 {children}
21 </main>
22 </ThemeProvider>
23 </body>
24 <GoogleTagManager gtmId={process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID!} />
25 </html>
26 );
27}
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.