Course contentsShow
← Web Development
Lesson 2499 of 2,98245. InternationalizationFree lesson

Detecting Locale from URL Patterns

Implement locale detection using URL structures like subdomains, path prefixes, or query parameters.

Detecting Locale from URL Patterns

You'll learn how to extract user locale preferences directly from URL structures to serve internationalized content.

While the Accept-Language header and navigator.language provide client-side locale hints, many modern web applications encode locale directly in the URL. This approach offers several advantages: it's explicit, shareable, bookmarkable, and works reliably across all browsers and server configurations.

Three Common URL Patterns

Subdomain-Based

The locale appears as a subdomain:

  • fr.example.com → French
  • de.example.com → German

Extract it by parsing window.location.hostname and checking the leftmost segment.

Path Prefix

The locale is the first segment of the URL path:

  • example.com/es/products → Spanish
  • example.com/ja/products → Japanese

Parse window.location.pathname and examine the first directory.

Query Parameter

The locale appears as a URL parameter:

  • example.com/products?lang=pt → Portuguese
  • example.com/products?locale=zh-CN → Chinese (Simplified)

Extract using URLSearchParams from the search string.

Detection Flow

Think of URL-based locale detection as reading an address label: the information is right there in the URL string, waiting to be parsed. Your code simply needs to look in the right "spot" based on which pattern your application uses.

Typically, you'd check the URL first (most explicit), then fall back to navigator.languages (user preference), and finally default to your application's base locale. This creates a clear hierarchy: explicit choice > implicit preference > safe default.

URL patterns are especially powerful for server-side rendering, SEO (search engines can discover language variants), and social media sharing (links preserve language context).

Key Takeaway: URL-based locale detection makes language selection explicit, shareable, and SEO-friendly by encoding locale information directly in subdomain, path, or query string structures.