Cookie, Google Analytics, Microsoft Clarity·

Cookie in Nuxt 3

How to use cookies without additional packages

Introduction to Cookies and Analytics

Cookies are small files stored on the user's device that allow websites to remember information about the visitor. Cookies are used to store various information about the user, including whether the user has consented to sending analytical data. Using analytical tools, we can track and analyze traffic and interactions on websites.

According to European Union laws, specifically the GDPR (General Data Protection Regulation), websites are required to obtain user consent before collecting any analytical data. This rule is enforced through cookie banners that inform users about the use of cookies and request their consent.

In practice, this means that when a user first loads the site, they are presented with a banner with information about cookies and options to consent or refuse. This information is stored in cookies so that it does not need to be displayed again on subsequent visits.

Our implementation uses Nuxt3, Nuxt UI and Tailwind CSS to create a user-friendly cookie banner. When the site is first loaded, the user is presented with information about cookies with two options: "Accept" and "Settings".

If the user clicks "Accept," analytical cookies are enabled, and the value true is stored in the cookies (name: cookieAnalytics). If the user chooses "Settings," they are presented with additional options to select which cookies they want to allow. Functional cookies are enabled by default and cannot be disabled, while analytical cookies are enabled by default but can be disabled.

Analytical data to Google Analytics or Microsoft Clarity is only sent when the user consents to the use of analytical cookies. Without this consent, data cannot be sent. Functionality can be verified via Developers Tools and the Networks tab.

home

settings

Example code for handling cookies:

plugins/gtag.client.js
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('app:mounted', (page) => {
    const checkAnalytics = checkIfCookiesAccepted()
    if (checkAnalytics) {
      addGoogleAnalytics()
      addMicrosoftClarity()
    }

    function checkIfCookiesAccepted() {
      const cookieAnalytics = useCookie('cookieAnalytics')
      return cookieAnalytics.value === 'true' || cookieAnalytics.value === true
    }
    function addGoogleAnalytics() {
      const { ID_GOOGLE_ANALYTICS } = useRuntimeConfig().public;

      function gtag() {
        window.dataLayer.push(arguments);
      }
      window.gtag = gtag;

      window.dataLayer = window.dataLayer || [];

      gtag("js", new Date());
      gtag("config", ID_GOOGLE_ANALYTICS,{
        send_page_view: true
      });

      useHead({
        script: [
          {
            src: `https://www.googletagmanager.com/gtag/js?id=${ID_GOOGLE_ANALYTICS}`,
            async: true,
          },
        ],
      });
    }
    function addMicrosoftClarity() {
      const { ID_MS_CLARITY } = useRuntimeConfig().public;
      const scriptTag = document.createElement('script')
      scriptTag.type = 'text/javascript'
      scriptTag.innerHTML = `(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "${ID_MS_CLARITY}");`

      window.clarity = window.clarity || function() {
        (window.clarity.q = window.clarity.q || []).push(arguments);
      };

      document.head.appendChild(scriptTag);
    }
  });
});

Project Features ✨

  • Nuxt 3 with Tailwind CSS
  • Nuxt UI (license for Nuxt UI Pro components is not included in the project)
  • Cookie banner
  • Data is sent only if the user confirms the processing of analytical data
  • Support for Google Analytics
  • Support for MS Clarity
  • Dark theme support

Project Preview

The project is available for download on GitHub and a preview of the functional project is available on a separate subdomain nuxt-cookie-analytics-ms-clarity.

Easy and Quick Installation

Download

  1. Download the project from GitHub:
git clone https://github.com/devpora/nuxtCookieAnalyticsMSClarity.git
  1. Navigate to the project:
cd nuxtCookieAnalyticsMSClarity

Setup

  1. Copy the sample .env.example to create a .env file for your environment:
cp .env.example .env
  1. Fill in the IDs from your Analytics and Clarity accounts:
ID_GOOGLE_ANALYTICS=ADD_YOUR_KEY
ID_MS_CLARITY=ADD_YOUR_KEY

Installation and Running

  1. Install dependencies:
yarn install
  1. Start the project:
yarn dev

That's all 🤩

Important Files

FileFunction
components/organisms/Cookie.vueCookie baner
plugins/gtag.client.jsPlugin for implementing Analytics and Clarity
utils/analytics.jsEvent sending

Register your project here to get a specific ID

Google Analytics

Analytical data about site visitors

Microsoft Clarity

Heatmaps and user behavior on the site

Conclusion

Implementing cookies and analytical tools in Nuxt3 is essential for improving user experience and collecting useful data about site visitors. Adhering to GDPR is critical to ensure the privacy of our users and meet legal requirements. By using a cookie banner and obtaining user consent, we can effectively use tools like Google Analytics and Microsoft Clarity while respecting the rights of our visitors.