@@ -80,7 +80,18 @@ function extractClientIp(req: NextRequest): string | undefined {
8080 return req . headers . get ( 'x-real-ip' ) ?? undefined
8181}
8282
83- function getCountryFromIp ( clientIp : string | undefined ) : string | null {
83+ function getCountryCode ( req : NextRequest ) : string | null {
84+ const cfCountry = req . headers . get ( 'cf-ipcountry' )
85+ if ( cfCountry && cfCountry !== 'XX' && cfCountry !== 'T1' ) {
86+ return cfCountry . toUpperCase ( )
87+ }
88+
89+ const vercelCountry = req . headers . get ( 'x-vercel-ip-country' )
90+ if ( vercelCountry && vercelCountry !== 'XX' ) {
91+ return vercelCountry . toUpperCase ( )
92+ }
93+
94+ const clientIp = extractClientIp ( req )
8495 if ( ! clientIp ) {
8596 return null
8697 }
@@ -248,8 +259,16 @@ export async function postChatCompletions(params: {
248259
249260 // For free mode requests, check if user is in US or Canada
250261 if ( isFreeModeRequest ) {
262+ const countryCode = getCountryCode ( req )
251263 const clientIp = extractClientIp ( req )
252- const countryCode = getCountryFromIp ( clientIp )
264+
265+ const cfHeader = req . headers . get ( 'cf-ipcountry' )
266+ const vercelHeader = req . headers . get ( 'x-vercel-ip-country' )
267+ const geoipResult = clientIp ? geoip . lookup ( clientIp ) ?. country ?? null : null
268+ logger . info (
269+ { cfHeader, vercelHeader, geoipResult, resolvedCountry : countryCode , clientIp : clientIp ? '[redacted]' : undefined } ,
270+ 'Free mode country detection' ,
271+ )
253272
254273 // If we couldn't determine country (null), allow the request (fail open)
255274 // This handles users behind VPNs, corporate proxies, or localhost
0 commit comments