Geo, short for geolocation, is the real-world geographic position of a device or user, typically expressed as latitude and longitude coordinates. To apply it to a Next.js site, you use the geolocation field in the request object of server-side functions like getServerSideProps or Route Handlers, which the hosting platform (e.g., Vercel) populates based on the visitor’s IP address.
Formula
The calculator above uses the haversine formula to compute the great-circle distance between your entered coordinates and the default location (New York City: 40.7128° N, 74.0060° W). The formula is:
a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
c = 2 ⋅ atan2( √a, √(1−a) )
d = R â‹… c
Where:
φ1, φ2are the latitudes of the two points (in radians)Δφis the difference in latitudesΔλis the difference in longitudesRis Earth’s mean radius (6,371 km)dis the distance between the points (in km)
In the calculator, the expression converts degrees to radians by multiplying by pi / 180. The result is rounded to two decimal places.
Worked Example
Using the default values from the calculator (latitude = 40.7128, longitude = -74.0060, which is New York City), the distance between the entered point and itself is zero. Let’s compute it step-by-step:
- Convert both latitudes to radians:
φ1 = 40.7128 × π/180 = 0.7105rad,φ2 = 0.7105rad - Convert both longitudes to radians:
λ1 = -74.0060 × π/180 = -1.2915rad,λ2 = -1.2915rad - Differences:
Δφ = 0,Δλ = 0 - Compute
a = sin²(0/2) + cos(0.7105) ⋅ cos(0.7105) ⋅ sin²(0/2) = 0 - Compute
c = 2 ⋅ atan2(√0, √1) = 2 ⋅ 0 = 0 - Distance
d = 6371 × 0 = 0.00 km
The calculator returns 0.00 km, as expected.
What Does Geo Mean in Web Development?
In web development, geo usually refers to geolocation — the process of identifying the geographic location of a website visitor. This can be done in two main ways:
- IP-based geolocation: The server looks up the visitor’s IP address in a database to estimate their country, city, and sometimes even latitude/longitude. This is approximate and can be off by miles, but it requires no user permission.
- Browser geolocation: The browser asks the user for permission to share their precise GPS or Wi-Fi-based location via the
navigator.geolocationAPI. This is much more accurate but requires explicit user consent.
For most Next.js sites, IP-based geolocation is the practical choice because it works on the server side, doesn’t annoy users with permission prompts, and is sufficient for personalizing content by country or region.
How to Get Geo Data in Next.js
Next.js runs on Vercel, Netlify, and other platforms that provide geolocation headers. The most common way is to read the request object in a server-side function. Here’s how:
1. Using getServerSideProps (Pages Router)
In the Pages Router, you can access the req object and look for the geolocation field. On Vercel, this field is automatically added:
export async function getServerSideProps({ req }) {
const geo = req.headers['x-vercel-ip-country'] || 'US';
return { props: { country: geo } };
}
But the more structured way is to use the geolocation object that Vercel injects into the request:
export async function getServerSideProps({ req }) {
// Vercel provides req.geolocation
const { country, city, latitude, longitude } = req.geolocation || {};
return { props: { country, city, latitude, longitude } };
}
2. Using Route Handlers (App Router)
In the App Router, you can use Route Handlers (API endpoints) with the NextRequest object:
// app/api/geo/route.js
import { NextResponse } from 'next/server';
export async function GET(request) {
const geo = request.geolocation; // available on Vercel
return NextResponse.json(geo);
}
3. Using Middleware
Middleware runs before the page is rendered, so it’s perfect for geo-based redirects or rewrites:
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
const country = request.geolocation?.country;
if (country === 'DE') {
return NextResponse.redirect(new URL('/de', request.url));
}
return NextResponse.next();
}
How to Choose the Right Geo Method
Choosing between IP-based and browser-based geolocation depends on your use case:
- Country-level personalization (language, currency, content) → IP-based is enough and requires no user interaction.
- Precise location for maps or local services → Use the browser’s
navigator.geolocationAPI with a clear permission prompt. - Compliance with regional laws (e.g., GDPR) → IP-based is often used to determine if a user is in the EU, but be aware that IP geolocation is not 100% accurate.
A common misconception is that IP geolocation is always accurate. In reality, IP databases can be wrong due to VPNs, proxies, or corporate networks. Always treat geo data as a hint, not a certainty.
Common Problems and Misconceptions
When implementing geo in Next.js, you might run into these issues:
- Geo data is undefined on localhost: Your local dev server doesn’t have the geolocation headers that Vercel adds. You need to mock the data or use a library like
@vercel/edgefor testing. - VPNs and proxies: Users can mask their location, so geo data may not reflect their true location.
- Performance: Using
getServerSidePropsfor every request adds latency. Consider using Edge Middleware or client-side detection for non-critical geo features. - Caching: If you cache pages, geo-based content might be served to the wrong users. Use
Vary: x-vercel-ip-countryheader to avoid this.
Alternatives to IP-Based Geo
If you need more accuracy or want to avoid server-side complexity, consider these alternatives:
- Client-side geolocation: Use the
navigator.geolocationAPI in auseEffecthook. This gives you GPS-level accuracy but requires user consent. - Third-party geo APIs: Services like ipapi or ipstack provide more detailed data (ISP, timezone, etc.) but require an API key and may have costs.
- Language-based detection: If you only need to serve content in the user’s language, you can use the
Accept-Languageheader instead of geo.
Frequently Asked Questions
Does Next.js have built-in geolocation?
Next.js itself doesn’t include geolocation, but the framework exposes the request object so you can read headers that hosting platforms like Vercel inject. On Vercel, you get req.geolocation with country, city, and coordinates. On other platforms, you may need to use a third-party API or a custom header.
How accurate is IP-based geolocation?
IP-based geolocation is typically accurate to the city level (about 50-100 km), but it can be off by hundreds of miles if the user is on a VPN or a corporate network. For country-level decisions, it’s usually reliable. For precise location, use the browser’s GPS API.
Can I use geo data in a static Next.js site?
No, because static pages are pre-rendered and don’t have access to the request at runtime. You would need to use client-side geolocation or a third-party API that runs in the browser. Alternatively, you can use Next.js’s Incremental Static Regeneration (ISR) with a fallback that fetches geo data on the client.
How do I test geo features locally?
You can mock the geolocation object in your code by checking if it exists and providing a fallback. For example, in getServerSideProps, you can use req.geolocation || { country: 'US' }. You can also use browser dev tools to override the navigator.geolocation API for client-side testing.
Is geolocation GDPR-compliant?
IP addresses are considered personal data under GDPR, so you must have a legal basis to process them. If you use IP-based geolocation for analytics or personalization, you should inform users in your privacy policy. Browser-based geolocation requires explicit consent, which is the safest approach.
Can I use geo to block users from certain countries?
Yes, you can use geo data in middleware to redirect or block users from specific countries. However, this is not foolproof because users can use VPNs. Also, be aware that blocking by country may have legal implications depending on your content and jurisdiction.
Related
Formula used
in lat | Latitude | ° | 40.7128 | -90 | 90 in lon | Longitude | ° | -74.0060 | -180 | 180 out dist | Distance (km) | km | 6371 * acos( sin(lat * pi / 180) * sin(40.7128 * pi / 180) + cos(lat * pi / 180) * cos(40.7128 * pi / 180) * cos(lon * pi / 180 - (-74.0060 * pi / 180)) ) | 2
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Philips DST7060/20 7000 Series Iron: Specs & Fit
- Coal Fueled Jet Aircraft: Could It Work?675 L
- Remote Desktop on Raspberry Pi: How to Enable It
- Word Select Last Line in Paragraph?
- Google Assistant IFTTT Recipes: 7 Useful Automations
- OLED TVs in Dark Rooms: Why They Look Better and When They Don’t