Files
Admin_dash/app/api/track/route.ts

45 lines
1.6 KiB
TypeScript
Raw Normal View History

2026-02-08 03:03:53 -05:00
import { NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import geoip from 'geoip-lite';
export async function POST(req: Request) {
try {
const body = await req.json();
const headers = req.headers;
// Get IP (proxies can complicate this, but X-Forwarded-For is standard)
const forwarded = headers.get('x-forwarded-for');
const ip = forwarded ? forwarded.split(',')[0] : '127.0.0.1'; // Fallback for dev
// Geo lookup
const geo = geoip.lookup(ip);
// Hash IP for privacy (simple hash for demo, salt in prod)
// For this personal dash, we might just store it or a simple hash
const ipHash = ip; // Storing raw IP for personal dash context, or hash if preferred.
if (geo) {
const db = await getDb();
await db.run(
`INSERT INTO visitors (ip_hash, city, country, lat, lon) VALUES (?, ?, ?, ?, ?)`,
ipHash, geo.city, geo.country, geo.ll[0], geo.ll[1]
);
} else {
// Fallback for localhost testing
if (ip === '127.0.0.1' || ip === '::1') {
const db = await getDb();
// Mock NYC for localhost
await db.run(
`INSERT INTO visitors (ip_hash, city, country, lat, lon) VALUES (?, ?, ?, ?, ?)`,
'localhost', 'New York', 'US', 40.7128, -74.0060
);
}
}
return NextResponse.json({ success: true });
} catch (error) {
console.error('Track error:', error);
return NextResponse.json({ success: false }, { status: 500 });
}
}