From 065dceaa7e2a5dffc133b6701f304a560db51f50 Mon Sep 17 00:00:00 2001 From: silentsilas Date: Mon, 27 Jan 2025 17:19:29 -0500 Subject: [PATCH] add hook for dark visitor analytics --- src/hooks.server.ts | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 5c5722b..ac4f52d 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -1,7 +1,31 @@ import { getModel } from '$lib/utils/search'; import { building } from '$app/environment'; -import type { Handle } from '@sveltejs/kit'; +import type { Handle, RequestEvent } from '@sveltejs/kit'; import { v4 as uuidv4 } from 'uuid'; +import { DARK_VISITORS_TOKEN } from '$env/static/private'; + +async function sendAnalytics(event: RequestEvent) { + try { + const headers = Object.fromEntries(event.request.headers.entries()); + + console.log(DARK_VISITORS_TOKEN); + + void fetch('https://api.darkvisitors.com/visits', { + method: 'POST', + headers: { + Authorization: `Bearer ${DARK_VISITORS_TOKEN}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + request_path: event.url.pathname, + request_method: event.request.method, + request_headers: headers + }) + }); + } catch (e) { + // Silent fail + } +} if (!building) { getModel().catch((error) => { @@ -18,10 +42,17 @@ export const handle: Handle = async ({ event, resolve }) => { // If no session exists, create a new one if (!sessionId) { sessionId = uuidv4(); - event.cookies.set('sessionId', sessionId, { path: '/', httpOnly: true, sameSite: 'strict', maxAge: 60 * 60 * 24 * 7 }); // 1 week + event.cookies.set('sessionId', sessionId, { + path: '/', + httpOnly: true, + sameSite: 'strict', + maxAge: 60 * 60 * 24 * 7 + }); // 1 week } // Add sessionId to locals for easy access in routes event.locals = { ...event.locals, sessionId }; + sendAnalytics(event); + return resolve(event); };