Redirecting Based on Language Change
What you'll learn: How to gracefully navigate users to localized URLs when they switch languages in multi-page applications.
In single-page apps, you can update content without reloading, but in traditional multi-page applications (MPAs), different language versions often live at distinct URLs—like /en/about vs /es/about. When a user changes their language preference, you need to redirect them to the corresponding page in the new locale.
Why Full-Page Redirects Matter
Think of it like switching train lines mid-journey. You can't just repaint the train car—you need to actually transfer to a different track. Similarly, when your Spanish content lives at a different URL than your English content, the browser must navigate to that new location.
Core Implementation Pattern
When the user clicks a language switcher, your code should:
- Detect the current page path (e.g.,
/en/products/123) - Extract the locale-neutral path (
/products/123) - Construct the new URL with the target locale (
/fr/products/123) - Perform the redirect using
window.location.href = newUrl
// User selected French from language picker
const currentPath = window.location.pathname; // "/en/products/123"
const newLocale = 'fr';
const pathWithoutLocale = currentPath.replace(/^\/[a-z]{2}\//, '/'); // "/products/123"
const newPath = `/${newLocale}${pathWithoutLocale}`;
window.location.href = newPath; // Full page reload to /fr/products/123
You'll typically combine this with cookie or localStorage updates (from lesson 2507) to persist the preference for future visits.
Key Takeaway: In multi-page apps, language changes require full redirects to localized URLs—extract the locale-neutral path, reconstruct with the new locale code, and update window.location.href to trigger navigation.