Skip to content

Instantly share code, notes, and snippets.

@arbaaz
Created June 15, 2023 12:19
Show Gist options
  • Select an option

  • Save arbaaz/11302c06d3ae58a6e34696ef77cddec2 to your computer and use it in GitHub Desktop.

Select an option

Save arbaaz/11302c06d3ae58a6e34696ef77cddec2 to your computer and use it in GitHub Desktop.

Revisions

  1. arbaaz created this gist Jun 15, 2023.
    51 changes: 51 additions & 0 deletions GoogleAnalytics.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    import { useEffect } from "react";

    import * as gtag from "lib/gtag";
    import { useRouter } from "next/router";
    import Script from "next/script";

    export default function GoogleAnalytics({ enabled }) {
    const router = useRouter();

    useEffect(() => {
    if (enabled) {
    const handleRouteChange = url => {
    gtag.pageview(url);
    };
    router.events.on("routeChangeComplete", handleRouteChange);
    return () => {
    router.events.off("routeChangeComplete", handleRouteChange);
    };
    }

    return () => {};
    }, [router.events, enabled]);

    if (!enabled) {
    return null;
    }

    return (
    <>
    <Script
    strategy="afterInteractive"
    src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
    />
    <Script
    id="gtag-init"
    strategy="afterInteractive"
    // eslint-disable-next-line jam3/no-sanitizer-with-danger
    dangerouslySetInnerHTML={{
    __html: `
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', '${gtag.GA_TRACKING_ID}', {
    page_path: window.location.pathname,
    });
    `,
    }}
    />
    </>
    );
    }
    17 changes: 17 additions & 0 deletions gtag.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID;

    // https://developers.google.com/analytics/devguides/collection/gtagjs/pages
    export const pageview = url => {
    window.gtag("config", GA_TRACKING_ID, {
    page_path: url,
    });
    };

    // https://developers.google.com/analytics/devguides/collection/gtagjs/events
    export const event = ({ action, category, label, value }) => {
    window.gtag("event", action, {
    event_category: category,
    event_label: label,
    value: value,
    });
    };