add hook for dark visitor analytics

This commit is contained in:
silentsilas 2025-01-27 17:19:29 -05:00
parent 8e2c52d3f8
commit 065dceaa7e
Signed by: silentsilas
GPG Key ID: 113DFB380F724A81
1 changed files with 33 additions and 2 deletions

View File

@ -1,7 +1,31 @@
import { getModel } from '$lib/utils/search'; import { getModel } from '$lib/utils/search';
import { building } from '$app/environment'; 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 { 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) { if (!building) {
getModel().catch((error) => { getModel().catch((error) => {
@ -18,10 +42,17 @@ export const handle: Handle = async ({ event, resolve }) => {
// If no session exists, create a new one // If no session exists, create a new one
if (!sessionId) { if (!sessionId) {
sessionId = uuidv4(); 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 // Add sessionId to locals for easy access in routes
event.locals = { ...event.locals, sessionId }; event.locals = { ...event.locals, sessionId };
sendAnalytics(event);
return resolve(event); return resolve(event);
}; };