Skip to content

Commit

Permalink
feat: add google analytics banner without measurement ID (#119)
Browse files Browse the repository at this point in the history
* feat: add google analytics banner without measurement ID

* gtag id added

* fix: cookie banner trigger

* fixed bug with cookie value

* removed unused import

* update with boolean undefined

* fix: add proper cookie text

* fix: adjust for deployment

* modified text and keep it white on all sites

* workaround for not working gtag

---------

Co-authored-by: LaurenzSommerlad <Laurenz.Sommerlad@gmail.com>
Co-authored-by: Cyro292 <amon@archi.de>
  • Loading branch information
3 people authored Aug 14, 2024
1 parent e7c3aa7 commit 9c7bcf5
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 1 deletion.
11 changes: 10 additions & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { Providers } from "./providers";
import "../styles/globals.css";
import { Header } from "@components/Header";
import Footer from "@components/Footer";
import GoogleAnalytics from "@components/GoogleAnalytics";
import CookieBanner from "@components/CookieBanner";
import { Suspense } from "react";

export default function RootLayout({
children,
Expand All @@ -11,11 +14,17 @@ export default function RootLayout({
}) {
return (
<html lang="en">
<Suspense>
<GoogleAnalytics GA_MEASUREMENT_ID="G-X80DYJS6SW" />
</Suspense>
<body>
<Providers>
<div className={inter.className}>
<Header />
<main>{children}</main>
<main>
{children}
<CookieBanner />
</main>
<Footer />
</div>
</Providers>
Expand Down
62 changes: 62 additions & 0 deletions components/CookieBanner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
"use client";

import Link from "next/link";
import { getLocalStorage, setLocalStorage } from "./lib/cookieStorage";
import { useState, useEffect } from "react";

export default function CookieBanner() {
const [cookieConsent, setCookieConsent] = useState<boolean | undefined>(undefined);

useEffect(() => {
const storedCookieConsent = getLocalStorage("cookie_consent", null);

setCookieConsent(storedCookieConsent);
}, [setCookieConsent]);

useEffect(() => {
if (typeof window.gtag === "function") {
const newValue = cookieConsent ? "granted" : "denied";
window.gtag("consent", "update", {
analytics_storage: newValue,
});
}

if (cookieConsent === undefined) return;
setLocalStorage("cookie_consent", cookieConsent);
}, [cookieConsent]);
return (
<div
className={`my-10 mx-auto max-w-max md:max-w-screen-sm
fixed bottom-0 left-0 right-0
flex px-3 md:px-4 py-3 justify-between items-center flex-col sm:flex-row gap-4
bg-gray-700 rounded-lg shadow z-50
${(cookieConsent === undefined || cookieConsent !== null) ? "hidden" : "flex"}`}
>
<div className="text-cente text-white">
<Link href="/info/cookies">
<h3 className="text-lg font-semibold mb-2">Cookie Policy</h3>
<p>
Tum.ai uses cookies to enhance your experience, including essential functions like logging in, saving preferences, and personalizing content. We also use Google Analytics to monitor site usage and improve our services. If you continue to use this site, you agree that we can place these types of cookies on your device. You can manage your cookie preferences at any time in your browser settings.
</p>
</Link>
</div>

<div className="flex gap-2">
<button
className="px-5 py-2 text-gray-300 rounded-md border-gray-900"
onClick={() => setCookieConsent(false)}
>
Decline
</button>
<button
className="bg-gray-900 px-5 py-2 text-white rounded-lg"
onClick={() => setCookieConsent(true)}
>
<p>Allow Cookies</p>
</button>
</div>
</div>
);
}
47 changes: 47 additions & 0 deletions components/GoogleAnalytics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"use client";
import Script from "next/script";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { pageview } from "./lib/gtagHelper";

export default function GoogleAnalytics({
GA_MEASUREMENT_ID,
}: {
GA_MEASUREMENT_ID: string;
}) {
const pathname = usePathname();
const searchParams = useSearchParams();

useEffect(() => {
const url = pathname + searchParams.toString();

pageview(GA_MEASUREMENT_ID, url);
}, [pathname, searchParams, GA_MEASUREMENT_ID]);
return (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
/>
<Script
id="google-analytics"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('consent', 'default', {
'analytics_storage': 'denied'
});
gtag('config', '${GA_MEASUREMENT_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</>
);
}
15 changes: 15 additions & 0 deletions components/lib/cookieStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-explicit-any */
import "client-only";

export function getLocalStorage(key: string, defaultValue: any){
const stickyValue = localStorage.getItem(key);

return (stickyValue !== null && stickyValue !== 'undefined')
? JSON.parse(stickyValue)
: defaultValue;
}

export function setLocalStorage(key: string, value: any){
localStorage.setItem(key, JSON.stringify(value));
}
7 changes: 7 additions & 0 deletions components/lib/gtagHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// components/lib/gtagHelper.tsx

export const pageview = (GA_MEASUREMENT_ID : string, url : string) => {
window.gtag("config", GA_MEASUREMENT_ID, {
page_path: url,
});
};
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@vercel/kv": "^1.0.1",
"axios": "^1.6.2",
"class-variance-authority": "^0.6.0",
"client-only": "^0.0.1",
"eslint": "^8.57.0",
"eslint-config-next": "^14.1.1",
"framer-motion": "^10.12.16",
Expand All @@ -45,6 +46,7 @@
"zod": "^3.22.4"
},
"devDependencies": {
"@types/gtag.js": "^0.0.20",
"@types/node": "20.3.1",
"@types/react": "18.2.12",
"autoprefixer": "^10.4.14",
Expand Down

0 comments on commit 9c7bcf5

Please sign in to comment.