Skip to content

Commit

Permalink
Use new goatcounter-js library in useAnalytics() hook
Browse files Browse the repository at this point in the history
  • Loading branch information
caleb531 committed Aug 6, 2024
1 parent 3223af0 commit d19becb
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 46 deletions.
53 changes: 7 additions & 46 deletions components/app/useAnalytics.ts
Original file line number Diff line number Diff line change
@@ -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<typeof window.goatcounter>
> {
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();
}
}, []);
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

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

0 comments on commit d19becb

Please sign in to comment.