Use Vercel headers for location.

This commit is contained in:
Mike Cao 2023-04-24 19:29:31 -07:00
parent c23373d164
commit 92ab391ef8
2 changed files with 23 additions and 7 deletions

View File

@ -56,12 +56,20 @@ export function getDevice(screen, os) {
}
}
export async function getLocation(ip) {
export async function getLocation(ip, req) {
// Ignore local ips
if (await isLocalhost(ip)) {
return;
}
if (process.env.VERCEL) {
return {
country: req.headers['x-vercel-ip-city'],
subdivision1: req.headers['x-vercel-ip-country-region'],
city: req.headers['x-vercel-ip-country'],
};
}
// Database lookup
if (!lookup) {
const dir = path.join(process.cwd(), 'geo');
@ -70,18 +78,21 @@ export async function getLocation(ip) {
}
const result = lookup.get(ip);
const country = result?.country?.iso_code ?? result?.registered_country?.iso_code;
const subdivision1 = result?.subdivisions?.[0]?.iso_code;
const subdivision2 = result?.subdivisions?.[1]?.names?.en;
const city = result?.city?.names?.en;
return { country, subdivision1, subdivision2, city };
if (result) {
return {
country: result.country?.iso_code ?? result?.registered_country?.iso_code,
subdivision1: result.subdivisions?.[0]?.iso_code,
subdivision2: result.subdivisions?.[1]?.names?.en,
city: result.city?.names?.en,
};
}
}
export async function getClientInfo(req: NextApiRequestCollect, { screen }) {
const userAgent = req.headers['user-agent'];
const ip = getIpAddress(req);
const location = await getLocation(ip);
const location = await getLocation(ip, req);
const country = location?.country;
const subdivision1 = location?.subdivision1;
const subdivision2 = location?.subdivision2;

View File

@ -7,6 +7,11 @@ const https = require('https');
const zlib = require('zlib');
const tar = require('tar');
if (process.env.VERCEL) {
console.log('Vercel environment detected. Skipping geo setup.');
process.exit(0);
}
const db = 'GeoLite2-City';
let url = `https://raw.githubusercontent.com/GitSquared/node-geolite2-redist/master/redist/${db}.tar.gz`;