Vercel provides several geolocation headers that you can use to determine a visitor's country. The most direct way is to use the x-vercel-ip-country
header 12.
Here's how you can access the country information in a Next.js App Router route handler:
export function GET(request: Request) {
const country = request.headers.get('x-vercel-ip-country');
return new Response(`Visitor from: ${country || 'Unknown country'}`);
}
Here's a more complete example that creates an API endpoint to return country information:
Vercel provides several geolocation headers 2:
x-vercel-ip-country
: Two-character ISO 3166-1 country codex-vercel-ip-continent
: Two-character continent code (AF, AN, AS, EU, NA, OC, SA)x-vercel-ip-city
: City namex-vercel-ip-country-region
: Region codex-vercel-ip-latitude
: Latitude coordinatex-vercel-ip-longitude
: Longitude coordinateYou can also access geolocation information in Edge Middleware using the geo
object 3:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Access country from the geo object
const country = request.geo?.country || 'Unknown';
// Add country to request headers
const response = NextResponse.next();
response.headers.set('x-country', country);
return response;
}
These headers are only available when your application is deployed on Vercel, and will not be present in local development unless you mock them.