add hook for dark visitor analytics

This commit is contained in:
silentsilas 2025-01-27 18:36:09 -05:00
parent 8e2c52d3f8
commit b76ab4e170
Signed by: silentsilas
GPG Key ID: 113DFB380F724A81
1 changed files with 31 additions and 2 deletions

View File

@ -1,7 +1,29 @@
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());
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 +40,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);
};