DEV Community

Cover image for Implementing Google Tag Manager and Analytics in Next.js
Alex Enes Zorlu
Alex Enes Zorlu

Posted on

Implementing Google Tag Manager and Analytics in Next.js

Hey there developers 👋 I have recently added Google Tag Manager (GTM) and Analytics to my Next.js app and could not believe how sleek this solution is. I want to share it with you so you can cook delicious cookies as well. 🍪

let's code

In this tutorial, we'll walk through the process of adding Google Tag Manager (GTM) and Google Analytics to your Next.js application. We'll use the @next/third-parties package, which provides optimized components for third-party libraries, and implement a cookie consent mechanism to ensure compliance with privacy regulations - GDPR.

Table of Contents

  1. Installation
  2. Creating a Cookie Consent Component
  3. Adding the Component to Your Layout
  4. Sending Custom Events
  5. Configuring Google Tag Manager
  6. Setting Environment Variables
  7. Conclusion

Installation

First, let's install the required packages. Open your terminal and run the following command:

npm install @next/third-parties js-cookie

Enter fullscreen mode Exit fullscreen mode

This will install the @next/third-parties package, which provides the Google Tag Manager component, and js-cookie, which we'll use to manage cookie consent.

Creating a Cookie Consent Component

Next, we'll bake our CookieConsent component that will handle the cookie consent logic and render the appropriate UI based on the user's choice. It's a lot easier than baking cookies!

Create a new file called CookieConsent.js in your components folder and add the following code:

'use client';

import { useState, useEffect } from 'react';
import { GoogleTagManager } from '@next/third-parties/google';
import Cookies from 'js-cookie';

const GTM_ID = process.env.NEXT_PUBLIC_GTM_ID;

export default function CookieConsent() {
  const [cookieState, setCookieState] = useState('not-answered');

  useEffect(() => {
    const state = Cookies.get('cookie-consent-state');
    if (state) setCookieState(state);
  }, []);

  const handleConsent = (state) => {
    Cookies.set('cookie-consent-state', state);
    setCookieState(state);
  };

  if (cookieState === 'not-answered') {
    return (
      <div className="fixed bottom-0 right-0 p-4 bg-gray-100 rounded-tl-lg">
        <p>We use cookies to improve your experience. Do you accept?</p>
        <button onClick={() => handleConsent('accepted')}>Accept</button>
        <button onClick={() => handleConsent('rejected')}>Reject</button>
      </div>
    );
  }

  if (cookieState === 'accepted') {
    return <GoogleTagManager gtmId={GTM_ID} />;
  }

  return (
    <button
      className="fixed bottom-4 right-4 p-2 bg-gray-200 rounded-full"
      onClick={() => setCookieState('not-answered')}
    >
      🍪
    </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

This component does the following:

  1. It uses the useState hook to manage the cookie consent state.
  2. On mount, it checks for an existing cookie consent state using js-cookie.
  3. It provides a UI for users to accept or reject cookies.
  4. If cookies are accepted, it renders the GoogleTagManager component.
  5. If cookies are rejected, it shows a small cookie icon that allows users to change their preference.

Adding the Component to Your Layout

Now that we have our CookieConsent component, it is time to add that to the mix, our application's layout. This ensures that the cookie consent banner and Google Tag Manager are available on all pages.

In your app/layout.js file, import and add the CookieConsent component:

import CookieConsent from '../components/CookieConsent';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}
        <CookieConsent />
      </body>
    </html>
  );
}

Enter fullscreen mode Exit fullscreen mode

Sending Custom Events

Here's where the fun begins - sending custom events!

One of the benefits of using Google Tag Manager is the ability to send custom events. These events can be used to track user interactions or important application states.

To send custom events to Google Tag Manager, you can use the sendGTMEvent function from @next/third-parties/google. Here's an example of how to use it:

import { sendGTMEvent } from '@next/third-parties/google';

function handleSubmit() {
  // Your form submission logic here

  // Send a custom event to GTM
  sendGTMEvent({ event: 'form_submitted', formName: 'newsletter' });
}

Enter fullscreen mode Exit fullscreen mode

You can call this function whenever you want to send an event to Google Tag Manager. For example, you might call it when a user submits a form, makes a purchase, or interacts with a specific feature of your application.

Configuring Google Tag Manager

To make use of the events you're sending, you'll need to configure your Google Tag Manager container. Here are the steps:

  1. Create a Google Tag Manager account and container if you haven't already.
  2. Set up tags for Google Analytics and any other services you want to use.
  3. Create triggers based on the custom events you're sending (e.g., 'form_submitted').
  4. Use these triggers to fire your tags at the appropriate times.
  5. Publish your GTM container.

Don't forget to test everything using GTM's preview mode. It's like having X-ray vision for your website!

Setting Environment Variables

To keep your Google Tag Manager ID secure and make it easy to use different IDs for different environments, you should use an environment variable.

Add your Google Tag Manager ID to your .env.local file:

NEXT_PUBLIC_GTM_ID=GTM-XXXXXXX

Enter fullscreen mode Exit fullscreen mode

Replace GTM-XXXXXXX with your actual GTM container ID.

Conclusion

Congratulations! You've successfully implemented Google Tag Manager and Analytics in your Next.js app. Let's recap what you've accomplished:

  1. We've installed the necessary packages.
  2. We've created a CookieConsent component that manages user consent for cookies and tracking.
  3. We've added this component to our application layout.
  4. We've set up a method for sending custom events to Google Tag Manager.
  5. We've outlined the steps for configuring Google Tag Manager.
  6. We've set up our GTM ID as an environment variable.

confetti

You're now tracking your app like a pro, all while respecting user privacy. Nice work!

Remember to test thoroughly, keep your privacy policy up to date, and have fun exploring your new analytics superpowers!

Happy coding, and may your bounce rates be ever in your favor! 😉

Top comments (0)