Performance: Geolocation and edge logic
This affects page load speed and responsiveness by deciding where and how geolocation logic runs, impacting server response time and client rendering.
import { cookies } from 'next/headers'; export const runtime = 'edge'; export async function GET() { const cookieStore = cookies(); const userLocation = cookieStore.get('user-location'); // Use edge logic to read location from cookie or fallback return new Response(JSON.stringify({ location: userLocation?.value || 'default' })); } // Client fetches precomputed location from edge API
'use client'; import { useState, useEffect } from 'react'; export default function Page() { const [location, setLocation] = useState(null); useEffect(() => { navigator.geolocation.getCurrentPosition(pos => { setLocation(pos.coords); }); }, []); return <div>{location ? `Lat: ${location.latitude}` : 'Loading...'}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side geolocation after load | Minimal DOM changes | 1 reflow after location set | Delays initial paint | [X] Bad |
| Edge runtime geolocation or precomputed location | No extra DOM operations | No reflows caused by location fetch | Faster initial paint | [OK] Good |
geo object on the request with location info.request.geo.country to get the country code.export function middleware(request) {
const country = request.geo?.country || 'unknown';
if (country === 'US') {
return Response.redirect(new URL('/us-home', request.url));
}
return Response.next();
}country to request.geo?.country or 'unknown'. For a US user, it is 'US'.export function middleware(request) {
const country = request.geo.country;
if (country = 'CA') {
return Response.redirect(new URL('/ca-home', request.url));
}
return Response.next();
}country = 'CA', which assigns 'CA' instead of comparing.=== to compare values, not =.export function middleware(request) {
const country = request.geo?.country || '';
const europeCountries = ['FR', 'DE', 'IT'];
const asiaCountries = ['JP', 'CN', 'IN'];
if (europeCountries.includes(country)) {
return Response.redirect(new URL('/eu-home', request.url));
} else if (asiaCountries.includes(country)) {
return Response.redirect(new URL('/asia-home', request.url));
}
return Response.next();
}includes to check membership and redirects accordingly, else continues normally.Pass the test and this pattern moves unknown