Added visitor analytics
This commit is contained in:
@@ -15,6 +15,8 @@ export const metadata: Metadata = {
|
||||
description: "My personal website",
|
||||
};
|
||||
|
||||
import { Analytics } from "../components/Analytics";
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
@@ -30,6 +32,7 @@ export default function RootLayout({
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
34
components/Analytics.tsx
Normal file
34
components/Analytics.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { usePathname } from 'next/navigation';
|
||||
|
||||
export function Analytics() {
|
||||
const pathname = usePathname();
|
||||
|
||||
useEffect(() => {
|
||||
// Send beacon on mount and path change
|
||||
const sendBeacon = async () => {
|
||||
try {
|
||||
// Point to the Admin Dashboard API
|
||||
// In prod, this URL needs to be the absolute URL of admin_dash
|
||||
// For local docker, standard localhost access might work if CORS allows,
|
||||
// or we route through a proxy.
|
||||
// For this personal setup, let's assume they are on same domain or localhost.
|
||||
await fetch('http://localhost:3000/api/track', { // TODO: Make this configurable
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ path: pathname, timestamp: Date.now() }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
keepalive: true,
|
||||
});
|
||||
} catch (e) {
|
||||
// Fail silently
|
||||
console.error('Analytics fail', e);
|
||||
}
|
||||
};
|
||||
|
||||
sendBeacon();
|
||||
}, [pathname]);
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user