Geolocation by IP
Explore how to use Vercel's geolocation IP headers to determine a user's country.
Playground
Your Location
Country: United States (US)
Region: OH
City: Columbus
This information is based on your IP address and may not be 100% accurate.
What I Learned
In this playground, I explored how to use Vercel's geolocation IP headers to determine a user's location. This feature allows us to access information about the user's country, city, and region without relying on client-side APIs or external services.
How It Works
Vercel automatically adds geolocation headers to incoming requests. We can access these headers server-side using Next.js's `headers()` function. Here's the key part of the code that retrieves the geolocation data:
function getGeolocationData() {
const headersList = headers();
const country = headersList.get('x-vercel-ip-country') || 'Unknown';
const countryName = country !== 'Unknown'
? new Intl.DisplayNames(['en'], { type: 'region' }).of(country) || 'Unknown'
: 'Unknown';
const city = headersList.get('x-vercel-ip-city') || 'Unknown';
const region = headersList.get('x-vercel-ip-country-region') || 'Unknown';
return { country, countryName, city, region };
}
This function retrieves the country code, city, and region from the headers. It also uses the `Intl.DisplayNames` API to convert the country code into a human-readable country name, with proper error handling.
Limitations and Considerations
While this method is fast and doesn't require any external API calls, it's important to note that:
- The accuracy of IP-based geolocation can vary.
- This feature is only available on Vercel's platform.
- Users with VPNs or proxy servers may show incorrect locations.
- The `Intl.DisplayNames` API might not support all country codes, so we need to handle potential undefined values.
Future Improvements
In the future, we could enhance this playground by:
- Adding a map visualization of the user's location.
- Providing more detailed information about the user's timezone.
- Implementing language suggestions based on the detected country.
- Adding a fallback mechanism for unsupported country codes in `Intl.DisplayNames`.