#Google Analytics with user consent

4 messages · Page 1 of 1 (latest)

toxic plinth
#

What do you think about this?

<script is:inline type="text/partytown">
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}

// Defining the default settings
gtag("consent", "default", {
    ad_storage: "denied",
    analytics_storage: "denied",
    ad_user_data: "denied",
    ad_personalization: "denied",
});

// Initializing Google Analytics tag
gtag("js", new Date());
gtag("config", "G-YDPPHYZESB", {
    anonymize_ip: true,
});

const denyButton = document.getElementById("cookie-deny-button");
const acceptButton = document.getElementById("cookie-accept-button");

if (denyButton instanceof HTMLButtonElement) {
    denyButton.addEventListener("click", () => {
        handleCookieConsent(false);
    });
}

if (acceptButton instanceof HTMLButtonElement) {
    acceptButton.addEventListener("click", () => {
        handleCookieConsent(true);
    });
}

// Global function to manage consent
const handleCookieConsent = (accepted) => {
    if (accepted) {
        gtag("consent", "update", {
            ad_storage: "granted",
            analytics_storage: "granted",
            ad_user_data: "granted",
            ad_personalization: "granted",
        });
    } else {
        gtag("consent", "update", {
            ad_storage: "denied",
            analytics_storage: "denied",
            ad_user_data: "denied",
            ad_personalization: "denied",
        });
    }

    localStorage.setItem("cookie-consent", accepted ? "granted" : "denied");
    document.getElementById("cookie-banner").style.display = "none";
};

const saved = localStorage.getItem("cookie-consent");

if (saved) {
    document.getElementById("cookie-banner").style.display = "none";
    handleCookieConsent(saved === "granted");
}

</script>

spice tulipBOT
#

Hi @toxic plinth. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Your code example looks good! You're using Partytown with Google Analytics in Astro, which is a great approach for performance optimization while handling user consent for cookies.

The type="text/partytown" attribute in your script tag tells Astro to run this script in a web worker rather than on the main thread, which helps improve your site's performance. Partytown is specifically designed to handle third-party scripts like analytics without slowing down your site Astro Partytown Integration.

Your implementation includes:

  1. Default consent settings that deny all tracking until user consent
  2. Proper initialization of Google Analytics with anonymized IP addresses
  3. Event listeners for consent buttons
  4. A consent management function that updates Google Analytics settings
  5. Local storage to remember user preferences

One thing to consider is configuring the Partytown integration to forward the dataLayer events properly. In your astro.config.mjs, you might want to add:

export default defineConfig({
  // ...
  integrations: [
    partytown({
      config: {
        forward: ['dataLayer.push'],
      },
    }),
  ],
});

This ensures that the dataLayer.push events are properly forwarded from the main thread to the web worker Partytown Configuration.

For a more eco-friendly approach, you might also consider lightweight analytics alternatives like Cabin, Fathom, or Plausible, which are mentioned in the Starlight documentation as being less power-intensive Eco-friendly docs.

#

Overall, your implementation is a solid approach to respecting user privacy while still collecting analytics data in an optimized way.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: