Detecting Language from URL
You'll learn: How to parse and apply language preferences embedded directly in your application's URLs, giving users shareable, bookmarkable localized experiences.
The Core Idea
When you store language information in the URL itself, users can share links that preserve their language choice, and bookmarks automatically remember preferences. This is more reliable than cookies or localStorage because the language becomes part of the resource identifier itself.
There are three common URL patterns for language detection:
Path-based: /fr/products or /products/fr
Subdomain-based: fr.example.com
Query parameter-based: /products?lang=fr
Think of it like addressing a letter: the language code tells the server (or client-side router) exactly which version of the content to deliver, right in the address.
Parsing the Language
Once you've chosen a pattern, extract the language code on page load:
// Path-based detection (e.g., /fr/products)
function getLangFromPath() {
const segments = window.location.pathname.split('/').filter(Boolean);
const firstSegment = segments[0];
// Check if first segment is a valid language code
const supportedLangs = ['en', 'fr', 'es', 'de'];
return supportedLangs.includes(firstSegment) ? firstSegment : 'en';
}
// Query parameter detection
function getLangFromQuery() {
const params = new URLSearchParams(window.location.search);
return params.get('lang') || 'en';
}
// Subdomain detection
function getLangFromSubdomain() {
const subdomain = window.location.hostname.split('.')[0];
const supportedLangs = ['en', 'fr', 'es', 'de'];
return supportedLangs.includes(subdomain) ? subdomain : 'en';
}
// Apply detected language
const detectedLang = getLangFromPath();
document.documentElement.lang = detectedLang;
Path-based is most SEO-friendly and user-friendly, while query parameters work well for simple overrides.
Key Takeaway: Embedding language codes in URLs creates shareable, bookmarkable localized experiences—parse them on page load and apply the detected language to your content rendering logic.