Files

45 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

2026-02-08 14:05:15 -05:00
import { NextResponse } from 'next/server';
import { logVisit } from '@/lib/db';
2026-02-08 14:05:15 -05:00
2026-02-08 23:18:21 -05:00
const ANALYTICS_KEY = process.env.ANALYTICS_KEY || 'default-analytics-key';
2026-02-08 14:05:15 -05:00
export async function POST(req: Request) {
try {
2026-02-08 23:18:21 -05:00
const analyticsKey = req.headers.get('X-Analytics-Key');
if (analyticsKey !== ANALYTICS_KEY) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 });
}
2026-02-08 14:05:15 -05:00
const body = await req.json();
2026-02-08 23:18:21 -05:00
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';
2026-02-08 14:05:15 -05:00
try {
logVisit(ip, body.path);
} catch (e) {
console.error('Failed to log visit to SQLite', e);
}
2026-02-08 14:05:15 -05:00
const adminUrl = process.env.ADMIN_DASH_URL || 'http://admin_dash:3000/api/track';
fetch(adminUrl, {
method: 'POST',
2026-02-08 23:18:21 -05:00
body: JSON.stringify({ path: body.path, timestamp: body.timestamp, ip }),
2026-02-08 14:05:15 -05:00
headers: {
'Content-Type': 'application/json',
2026-02-08 23:18:21 -05:00
'X-Forwarded-For': ip,
2026-02-08 14:05:15 -05:00
},
}).catch(e => console.error('Relay failed', e));
return NextResponse.json({ success: true });
2026-02-08 23:18:21 -05:00
} catch {
return NextResponse.json({ success: false, error: 'Bad request' }, { status: 400 });
2026-02-08 14:05:15 -05:00
}
}