Locale-Specific Redirections

Illustrate how to redirect users to locale-specific routes by detecting the user's language preferences and modifying routes accordingly.
// Function to perform locale-specific redirection
function redirectToLocale() {
  // Get user's preferred language (first language preference)
  const userLang = navigator.language || navigator.userLanguage;

  // Map language codes (ISO 639-1) to specific locale routes
  const localeRoutes = {
    'en': '/en', // English
    'es': '/es', // Spanish
    'fr': '/fr', // French
    'de': '/de', // German
    // Add more language-route mappings as required

  // Extract language code prefix (example: 'en-US' -> 'en')
  const languageCode = userLang.split('-')[0];

  // Redirect to the corresponding route if a mapping exists
  if (localeRoutes[languageCode]) {
    window.location.pathname = localeRoutes[languageCode];
  } else {
    // If no mapping exists, redirect to a default route
    window.location.pathname = '/en';

// Call the redirect function on page load or as needed
This code defines a function called 'redirectToLocale' which performs locale-specific redirection by using the browser's language preferences. It maps ISO 639-1 language codes to predefined routes and redirects the user to the corresponding path. If the language doesn't have a specific route, it redirects to a default one. The 'redirectToLocale' function is then called to automatically redirect the user upon page load or whenever appropriate.