How We Added IP-Based Language Detection in 3 Minutes
The Challenge
You want your Next.js app to automatically detect the user's language based on their location. Sounds complex, right? You might think you need:
- Third-party IP geolocation APIs
- Complex database lookups
- Expensive geolocation services
- Additional API calls on every page load
The Reality: It's Actually Super Simple
Modern hosting platforms like Vercel and Cloudflare already detect the user's country for every request. They include this information in request headers—completely free, with zero additional API calls!
The Solution: 3 Simple Steps
Step 1: Create a Country-to-Language Mapper (2 minutes)
// src/lib/i18n/country-to-language.ts
export function getLanguageFromCountry(countryCode: string): Language {
// Map common countries to languages
if (['BR', 'PT'].includes(countryCode)) return 'pt';
if (['ES', 'MX', 'AR'].includes(countryCode)) return 'es';
if (['IT'].includes(countryCode)) return 'it';
// ... and so on
return 'pt'; // Default
}
Step 2: Add Middleware (2 minutes)
// src/middleware.ts
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Get country from headers (Vercel/Cloudflare provides this!)
const countryCode = request.headers.get('x-vercel-ip-country');
if (countryCode) {
const language = mapCountryToLanguage(countryCode);
response.cookies.set('detected-lang', language);
}
return response;
}
That's it! The middleware runs automatically on every request and sets a cookie.
Step 3: Update Your I18n Provider (1 minute)
// Read from cookie instead of defaulting
const cookieLang = getLanguageFromCookie();
const detectedLang = cookieLang || 'pt'; // Fallback to default
Why This Is Brilliant
✅ Zero cost - No API calls, no third-party services
✅ Zero latency - Headers are already in the request
✅ Zero complexity - Just read headers and map countries
✅ Works everywhere - Vercel and Cloudflare both support this
✅ Non-intrusive - Falls back gracefully if headers aren't available
The Magic Headers
When you deploy on Vercel, you get:
-
x-vercel-ip-country- The user's country code
When you use Cloudflare, you get:
-
cf-ipcountry- The user's country code
Both platforms detect this automatically. No configuration needed!
Real-World Flow
- User from Brazil visits your site
- Vercel/Cloudflare adds
x-vercel-ip-country: BRheader - Your middleware reads
BR→ maps topt→ sets cookie - Your app shows Portuguese content
- User switches to English via selector → cookie updates
- Next visit → reads cookie → remembers preference
The Result
Before: Default language for everyone, manual selection required
After: Automatic detection with smart fallbacks
Time invested: ~5 minutes
Lines of code: ~100
Complexity: Minimal
User experience: Significantly improved ✨
TL;DR: Don't overthink it. Modern hosting platforms already give you geolocation for free. Just read the headers and map countries to languages. Done! 🎉
Top comments (0)