Skip to content

Commit

Permalink
add analytics
Browse files Browse the repository at this point in the history
  • Loading branch information
Pinwheeler committed Dec 29, 2024
1 parent 76fb174 commit 5c28c14
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 0 deletions.
Empty file added app/analytics.ts
Empty file.
10 changes: 10 additions & 0 deletions app/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// global.d.ts
interface Cookiebot {
consents: {
given: string[];
};
}

interface Window {
Cookiebot?: Cookiebot;
}
49 changes: 49 additions & 0 deletions app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import {
Outlet,
Scripts,
ScrollRestoration,
useLocation,
useRouteError,
} from "@remix-run/react";
import ReactGA from "react-ga4";
import { useEffect } from "react";

import "~/styles/global.css";
import layoutStyles from "~/styles/layout.css?url";
Expand All @@ -24,9 +27,55 @@ export const meta: MetaFunction = () => [
export const links: LinksFunction = () => [
{ rel: "stylesheet", href: layoutStyles },
{ rel: "stylesheet", href: errorStyles },
{ rel: "icon", href: "/favicon.ico" },
];

export const initGA = () => {
ReactGA.initialize("G-SS06K698MP"); // Replace with your Measurement ID
};

export const logPageView = (path: string) => {
ReactGA.send({ hitType: "pageview", page: path });
};

function App() {
const location = useLocation();

useEffect(() => {
if (!document.getElementById("Cookiebot")) {
const script = document.createElement("script");
script.src = "https://consent.cookiebot.com/uc.js";
script.id = "Cookiebot";
script.setAttribute("data-cbid", "5c963d7c-d540-4606-b8f7-b1618d8c8fb4");
script.type = "text/javascript";
script.async = true;
document.head.appendChild(script);
}
return () => {
const script = document.getElementById("Cookiebot");
if (script) {
document.head.removeChild(script);
}
};
}, []);

useEffect(() => {
const Cookiebot = window.Cookiebot;

// Listen for Cookiebot consent changes
window.addEventListener("CookieConsentDeclaration", () => {
if (Cookiebot?.consents.given.includes("statistics")) {
// Enable Google Analytics if consent is given
initGA();
logPageView(location.pathname);
}
});

return () => {
window.removeEventListener("CookieConsentDeclaration", () => {});
};
}, [location.pathname]);

return (
<html lang="en">
<head>
Expand Down
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"ramda": "^0.30.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-ga4": "^2.1.0",
"remix-auth": "^3.7.0",
"remix-auth-form": "^1.5.0",
"twin.macro": "^3.4.1"
Expand Down

0 comments on commit 5c28c14

Please sign in to comment.