DEV Community

alyson farias
alyson farias

Posted on

How We Added IP-Based Language Detection in 5 Minutes

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
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

  1. User from Brazil visits your site
  2. Vercel/Cloudflare adds x-vercel-ip-country: BR header
  3. Your middleware reads BR → maps to pt → sets cookie
  4. Your app shows Portuguese content
  5. User switches to English via selector → cookie updates
  6. 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)