Support Cloudflare headers for city and region.

This commit is contained in:
Mike Cao 2023-08-06 22:52:58 -07:00
parent f48720c915
commit f57fbe6ba1
3 changed files with 12 additions and 13 deletions

View File

@ -3,6 +3,7 @@ import { getClientIp } from 'request-ip';
import { browserName, detectOS } from 'detect-browser';
import isLocalhost from 'is-localhost-ip';
import maxmind from 'maxmind';
import { safeDecodeURIComponent } from 'next-basics';
import {
DESKTOP_OS,
@ -65,20 +66,18 @@ export async function getLocation(ip, req) {
// Cloudflare headers
if (req.headers['cf-ipcountry']) {
return {
country: req.headers['cf-ipcountry'],
country: safeDecodeURIComponent(req.headers['cf-ipcountry']),
subdivision1: safeDecodeURIComponent(req.headers['cf-region-code']),
city: safeDecodeURIComponent(req.headers['cf-ipcity']),
};
}
// Vercel headers
if (req.headers['x-vercel-ip-country']) {
const country = req.headers['x-vercel-ip-country'];
const region = req.headers['x-vercel-ip-country-region'];
const city = req.headers['x-vercel-ip-city'];
return {
country,
subdivision1: region,
city: city ? decodeURIComponent(city) : undefined,
country: safeDecodeURIComponent(req.headers['x-vercel-ip-country']),
subdivision1: safeDecodeURIComponent(req.headers['x-vercel-ip-country-region']),
city: safeDecodeURIComponent(req.headers['x-vercel-ip-city']),
};
}

View File

@ -90,7 +90,7 @@
"maxmind": "^4.3.6",
"moment-timezone": "^0.5.35",
"next": "13.3.1",
"next-basics": "^0.35.0",
"next-basics": "^0.36.0",
"node-fetch": "^3.2.8",
"npm-run-all": "^4.1.5",
"react": "^18.2.0",

View File

@ -6371,10 +6371,10 @@ natural-compare@^1.4.0:
resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==
next-basics@^0.35.0:
version "0.35.0"
resolved "https://registry.yarnpkg.com/next-basics/-/next-basics-0.35.0.tgz#aa68fd35a0e3fbabfdaf570cd092b6a7cf8df6f5"
integrity sha512-yqXZMLe109hSJ8sebI/f2m1XNnVuQowpELOhZSGOFOmLfvUyFBAEi0ULdqX1eb8xbttLgjcrumrZfMgmEwuCPw==
next-basics@^0.36.0:
version "0.36.0"
resolved "https://registry.yarnpkg.com/next-basics/-/next-basics-0.36.0.tgz#b1675c3f2b98df2fec8df605095dab7d17f9dc7b"
integrity sha512-Nwou8pCjFuoD/ZxUw9iKC7hhZeWbo/ng0ze74yck3W89MNc/CepwCDziflAHY5XcmIVNmpXOCu9OfmzTdVRPWQ==
dependencies:
bcryptjs "^2.4.3"
jsonwebtoken "^9.0.0"