Implement internationalized routing in Next.js without the built-in i18n. Write custom middleware that detects geo-IP from Vercel headers and rewrites French users from /en to /fr unless they have a NEXT_LOCALE cookie overriding the geo-detection.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The middleware reads the X-Vercel-IP-Country header to detect French users and rewrites URLs from /en to /fr unless a NEXT_LOCALE cookie explicitly overrides this, providing a compliant i18n routing solution without Next.js built-in i18n.
Below is a simple middleware.ts example for Next.js (using the new app/ router or Next 12+ with middleware support) that:
Reads the NEXT_LOCALE cookie (if present).
Otherwise checks the X-Vercel-IP-Country header (set automatically on Vercel).
If the path currently begins with /en, and the user is detected as French (FR), it rewrites to the equivalent /fr path—unless NEXT_LOCALE overrides with en.
Leaves everything else untouched.
You can adapt it for your own locale detection or additional edge cases.
ts
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
/**
* Helper to parse the incoming URL path prefix, e.g. "/en", "/fr".
*/
function getCurrentLocaleFromPath(pathname: string): string | null {
const segments = pathname.split('/')
// segments[0] is empty since path starts with "/"
return segments[1] || null
}
/**
* If you want to manage additional locales, list them here:
*/
const SUPPORTED_LOCALES = ['en', 'fr']
const DEFAULT_LOCALE = 'en' // or change as needed
export function middleware(req: NextRequest) {
const { nextUrl, cookies, headers } = req
const pathname = nextUrl.pathname
// Skip non-page routes (assets, etc.) if desired:
// (You can also configure `matcher` below.)
if (pathname.startsWith('/_next') || pathname.match(/\.[a-zA-Z]+$/)) {
return NextResponse.next()
}
// Check if user has a locale cookie.
const localeCookie = cookies.get('NEXT_LOCALE')?.value
const userLocale = localeCookie || null
// Check geolocation from Vercel header (e.g. "FR", "US", etc.)
const geoCountry = headers.get('x-vercel-ip-country')
// Determine the current path locale if it exists.
const currentLocale = getCurrentLocaleFromPath(pathname)
// If no locale in path, we could optionally redirect to a default one:
if (!currentLocale || !SUPPORTED_LOCALES.includes(currentLocale)) {
// E.g. if path is "/about", rewrite to "/en/about" or similar
const rewriteUrl = new URL(`/${DEFAULT_LOCALE}${pathname}`, req.url)
return NextResponse.rewrite(rewriteUrl)
}
// If a user has a NEXT_LOCALE cookie, respect it.
if (userLocale && userLocale !== currentLocale && SUPPORTED_LOCALES.includes(userLocale)) {
// Rewrite to the locale from the cookie
const rewriteUrl = new URL(`/${userLocale}${pathname.slice(currentLocale.length + 1) || ''}`, req.url)
return NextResponse.rewrite(rewriteUrl)
}
// If the user is in France, country code "FR", and currently on "/en/*",
// rewrite to the "/fr/*" equivalent, unless cookie says "en".
if (!userLocale && geoCountry === 'FR' && currentLocale === 'en') {
const rewriteUrl = new URL(`/fr${pathname.slice(currentLocale.length + 1) || ''}`, req.url)
return NextResponse.rewrite(rewriteUrl)
}
// Otherwise, proceed as normal
return NextResponse.next()
}
// Configure which paths the middleware runs on.
// Below excludes _next and all files with an extension.
export const config = {
matcher: [
'/((?!_next/|.*\\..*).*)'
]
}
How it works:
If a visitor hits /en/some-page with X-Vercel-IP-Country: FR, they’ll be rewritten to /fr/some-page unless they have NEXT_LOCALE=en set.
If a visitor has NEXT_LOCALE=fr, they’ll be sent to /fr/... even if they originally navigated to /en/....
If a visitor requests a path without a locale prefix, the middleware rewrites them to the default locale (/en in the example above), but you can change that logic as needed.
Feel free to adjust the matching logic, default locale, or add more locales and country overrides.