Files
Webserver/app/api/analytics/route.ts
Shivam Patel 4a01928fe7
All checks were successful
Deploy Website / build-and-deploy (push) Successful in 1m9s
Add SQLite visitor IP logging to /server_storage
Log visitor IPs and paths to a local SQLite database via the existing
analytics API route, persisted at /server_storage/visitors.db in Docker
(falls back to ./visitors.db in dev).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 00:04:45 -05:00

45 lines
1.5 KiB
TypeScript

import { NextResponse } from 'next/server';
import { logVisit } from '@/lib/db';
const ANALYTICS_KEY = process.env.ANALYTICS_KEY || 'default-analytics-key';
export async function POST(req: Request) {
try {
const analyticsKey = req.headers.get('X-Analytics-Key');
if (analyticsKey !== ANALYTICS_KEY) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 });
}
const body = await req.json();
if (typeof body.path !== 'string' || typeof body.timestamp !== 'number') {
return NextResponse.json({ success: false, error: 'Invalid input' }, { status: 400 });
}
const headers = req.headers;
const forwarded = headers.get('x-forwarded-for');
const ip = forwarded ? forwarded.split(',')[0].trim() : 'unknown';
try {
logVisit(ip, body.path);
} catch (e) {
console.error('Failed to log visit to SQLite', e);
}
const adminUrl = process.env.ADMIN_DASH_URL || 'http://admin_dash:3000/api/track';
fetch(adminUrl, {
method: 'POST',
body: JSON.stringify({ path: body.path, timestamp: body.timestamp, ip }),
headers: {
'Content-Type': 'application/json',
'X-Forwarded-For': ip,
},
}).catch(e => console.error('Relay failed', e));
return NextResponse.json({ success: true });
} catch {
return NextResponse.json({ success: false, error: 'Bad request' }, { status: 400 });
}
}