diff --git a/components/app/useAnalytics.ts b/components/app/useAnalytics.ts index 4f48399..7d1e9e0 100644 --- a/components/app/useAnalytics.ts +++ b/components/app/useAnalytics.ts @@ -1,56 +1,17 @@ +import * as goatcounter from 'goatcounter-js'; import { useEffect } from 'react'; -// Define a basic type for the goatcounter global -declare global { - interface Window { - goatcounter?: { - count: (options: object) => void; - }; - } -} - -// Resolve a promise when GoatCounter is fully loaded and ready to use on the -// page -export async function getGoatcounter(): Promise< - NonNullable -> { - return new Promise((resolve) => { - if (window.goatcounter) { - resolve(window.goatcounter); - } else { - const script = document.createElement('script'); - script.addEventListener('load', () => { - if (window.goatcounter) { - resolve(window.goatcounter); - } else { - console.log('goatcounter script loaded but global not available'); - } - }); - script.async = true; - script.dataset.goatcounter = `https://${process.env.NEXT_PUBLIC_ANALYTICS_SITE_ID}.goatcounter.com/count`; - script.dataset.goatcounterSettings = JSON.stringify({ no_onload: true }); - script.src = 'https://gc.zgo.at/count.v4.js'; - script.crossOrigin = 'anonymous'; - script.integrity = - 'sha384-nRw6qfbWyJha9LhsOtSb2YJDyZdKvvCFh0fJYlkquSFjUxp9FVNugbfy8q1jdxI+'; - document.head.appendChild(script); - } - }); -} - -// Count a single pageview with GoatCounter -export async function countPageview() { - const goatcounter = await getGoatcounter(); - goatcounter.count({ - path: location.pathname + location.search + location.hash - }); -} +goatcounter.initialize({ + scriptVersion: 4, + endpointUrl: `https://${process.env.NEXT_PUBLIC_ANALYTICS_SITE_ID}.goatcounter.com/count`, + settings: { no_onload: true } +}); // Use the function useAnalytics() { useEffect(() => { if (process.env.NEXT_PUBLIC_ANALYTICS_SITE_ID) { - countPageview(); + goatcounter.count(); } }, []); } diff --git a/package.json b/package.json index 3663cb9..68d8f88 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "clsx": "^2.1.1", "date-fns": "^3.6.0", "deep-object-diff": "^1.1.9", + "goatcounter-js": "1.0.0-beta.8", "lodash-es": "^4.17.21", "next": "^14.2.4", "next-pwa": "^5.6.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6787ec5..035e2b9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -35,6 +35,9 @@ dependencies: deep-object-diff: specifier: ^1.1.9 version: 1.1.9 + goatcounter-js: + specifier: 1.0.0-beta.8 + version: 1.0.0-beta.8 lodash-es: specifier: ^4.17.21 version: 4.17.21 @@ -5729,6 +5732,11 @@ packages: pinkie-promise: 2.0.1 dev: false + /goatcounter-js@1.0.0-beta.8: + resolution: {integrity: sha512-MybyBFrGGO5YeuuDLgwi3gntgvKE5ijM0wBKBfWLqXWXE/HOqUmSTftAW7vnUW9kZaW1s8ZglqTqwY1+xi993Q==} + engines: {node: '>=18.0.0'} + dev: false + /gopd@1.0.1: resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==} dependencies: