DEV Community

Cover image for How to Set Up User Cookies and Connect Google Analytics in Your React App
frank edekobi
frank edekobi

Posted on

How to Set Up User Cookies and Connect Google Analytics in Your React App

Question: What is this tutorial about?

This tutorial is about setting up user cookies in your web application and connecting it to the Google Analytics platform.

Why go through all this stress?
Because this setup allows you to track how users navigate your application for free.

Who is this tutorial for?
Anyone with a basic knowledge of React and Typescript

So if you think it's worth the stress, LET'S GET STARTED!!!

Introduction

For those unaware, Google Analytics is a powerful tool that offers a wide range of features for collecting and analyzing data from your web platform. However, the abundance of options can be overwhelming, especially when you first encounter the dashboard and its numerous use cases. One of my favorite applications of Google Analytics is setting up user cookies on my web application and connecting them to the Google Analytics platform. This capability allows you to track how users navigate your application for free. With a little patience and a step-by-step approach, you can easily set this up and gain valuable insights into user behavior.

In this tutorial, we'll walk you through setting up user cookies in your React app and connecting them to Google Analytics. We'll cover how to request user consent for different types of cookies and send this data to Google Analytics using the Global Site Tag (gtag.js).

Prerequisites

  • Basic knowledge of React.
  • A Google Analytics account. If you don't have one, follow this guide on setting up a Google Analytics account for User consent.

Google tag

  • Add the Google Tag (gtag.js) to Your HTML First, add the Google Tag (gtag.js) to your public/index.html file:
<!-- Google tag (gtag.js) -->
<script
  async
  src="https://www.googletagmanager.com/gtag/js?id=YOURGOOGLETAG"
></script>
<script>
  window.dataLayer = window.dataLayer || []
  function gtag() {
    dataLayer.push(arguments)
  }
  gtag('js', new Date())

  gtag('config', 'YOURGOOGLETAG')
</script>
Enter fullscreen mode Exit fullscreen mode
  • Extend Global Types with global.d.ts Create or update the global.d.ts file to extend the global window object, allowing TypeScript to recognize the gtag function:
declare global {
  interface Window {
    gtag: (
      command: string,
      action: string,
      params?: { [key: string]: any }
    ) => void
  }
}

export {} // Ensures the file is treated as a module
Enter fullscreen mode Exit fullscreen mode
  • Set Up Your tsconfig.json Ensure your tsconfig.json includes the correct configuration to support the necessary TypeScript features:

include the global.d.ts

{
  "compilerOptions": {
    ...
  },
  "include": ["src/**/*", ".d.ts", "global.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}
Enter fullscreen mode Exit fullscreen mode
  • Create the Consent Banner Component The ConsentBanner component handles user consent for various types of cookies and communicates this information to Google Analytics: Use or restyle however you wish
import { useEffect, useState, FC } from 'react'
import { getUserCookies, setUserCookies } from '../../../constants/global'

const ConsentBanner: FC = () => {
  const [isVisible, setIsVisible] = useState<boolean>(false)
  const [showPreferences, setShowPreferences] = useState<boolean>(false)
  const [preferences, setPreferences] = useState<{
    essential: boolean
    analytics: boolean
    userdata: boolean
    personalization: boolean
    marketing: boolean
  }>({
    essential: true,
    analytics: false,
    marketing: false,
    personalization: false,
    userdata: false
  })

  useEffect(() => {
    const consent = getUserCookies()
    if (!consent) {
      setIsVisible(true)
    }
  }, [])

  const handleAcceptAll = (): void => {
    setPreferences({
      essential: true,
      analytics: true,
      marketing: true,
      personalization: true,
      userdata: true
    })
    setUserCookies(preferences)
    window.gtag('consent', 'update', {
      ad_storage: 'granted',
      analytics_storage: 'granted',
      ad_user_data: 'granted',
      ad_personalization: 'granted',
      wait_for_update: 500
    })
    setIsVisible(false)
  }

  const handleShowPreferences = (): void => {
    setShowPreferences(true)
  }

  const handleAcceptPreferences = (): void => {
    setUserCookies(preferences)
    window.gtag('consent', 'update', {
      ad_storage: preferences.marketing ? 'granted' : 'denied',
      analytics_storage: preferences.analytics ? 'granted' : 'denied',
      ad_user_data: preferences.userdata ? 'granted' : 'denied',
      ad_personalization: preferences.personalization ? 'granted' : 'denied',
      wait_for_update: 500
    })
    setIsVisible(false)
  }

  const handleCheckboxChange = (
    event: React.ChangeEvent<HTMLInputElement>
  ): void => {
    const { name, checked } = event.target
    setPreferences((prev) => ({ ...prev, [name]: checked }))
  }

  if (!isVisible) return null

  return (
    <div style={styles.banner} className="f-column-10 py-4">
      <p style={styles.text}>
        We use cookies to enhance your experience. Please choose your preferences:
      </p>
      {showPreferences ? (
        <div
          style={styles.checkboxContainer}
          className="grid-wrapper-45 gap-33 aic py-4"
        >
          <label className="f-row-7">
            <input
              type="checkbox"
              name="essential"
              checked={preferences.essential}
              readOnly
            />
            Essential Cookies (required)
          </label>
          <label className="f-row-7">
            <input
              type="checkbox"
              name="analytics"
              checked={preferences.analytics}
              onChange={handleCheckboxChange}
            />
            Analytics Cookies
          </label>
          <label className="f-row-7">
            <input
              type="checkbox"
              name="marketing"
              checked={preferences.marketing}
              onChange={handleCheckboxChange}
            />
            Marketing Cookies
          </label>
          <label className="f-row-7">
            <input
              type="checkbox"
              name="personalization"
              checked={preferences.personalization}
              onChange={handleCheckboxChange}
            />
            Tailored Content Cookies
          </label>
          <label className="f-row-7">
            <input
              type="checkbox"
              name="userdata"
              checked={preferences.userdata}
              onChange={handleCheckboxChange}
            />
            User Data Cookies
          </label>
        </div>
      ) : null}
      <div style={styles.buttonContainer}>
        <button
          style={styles.button}
          onClick={handleAcceptAll}
          aria-label="accept all cookies"
        >
          Accept All
        </button>
        <button
          style={styles.button}
          onClick={handleShowPreferences}
          aria-label="customize cookie preferences"
        >
          Customize Preferences
        </button>
        {showPreferences && (
          <button
            style={styles.button}
            onClick={handleAcceptPreferences}
            aria-label="save cookies"
          >
            Save Preferences
          </button>
        )}
      </div>
    </div>
  )
}

const styles = {
  banner: {
    position: 'fixed' as 'fixed',
    bottom: '0',
    left: '0',
    right: '0',
    backgroundColor: '#141414',
    color: '#fff',
    padding: '10px',
    textAlign: 'center' as 'center',
    zIndex: 1000
  },
  text: {
    margin: '0 0 10px'
  },
  checkboxContainer: {
    textAlign: 'left' as 'left',
    margin: '10px auto',
    maxWidth: '500px'
  },
  buttonContainer: {
    display: 'flex' as 'flex',
    justifyContent: 'center' as 'center',
    gap: '10px'
  },
  button: {
    backgroundColor: '#007BFF',
    color: '#fff',
    border: 'none',
    padding: '10px 20px',
    cursor: 'pointer',
    borderRadius: '5px'
  }
}

export default ConsentBanner
Enter fullscreen mode Exit fullscreen mode

Conclusion

This tutorial covered setting up user cookies in your React application and connecting them to Google Analytics. Remember, getting consent from users is crucial for compliance with privacy regulations.

Top comments (0)