Locale Switching Without Losing Context
What you'll learn: How to preserve the user's exact location and state when they switch languages on your site.
When a user clicks your language switcher to change from English to Spanish, they shouldn't be rudely teleported back to your homepage. Instead, they should stay on the same page—an article, a search results screen, or a product listing—with all their filters, search terms, and scroll position intact.
The Core Problem
Imagine you're deep in a shopping site: you've filtered by size, sorted by price, and scrolled halfway through page 3 of results. You switch from English to French... and suddenly you're back at the homepage with everything reset. Frustrating, right?
The solution is to carry over the current path and query parameters when constructing your locale-switch URLs.
Implementation Pattern
When rendering language switcher links, take the current URL structure and swap only the locale portion:
// Current URL: /en/products?category=shoes&sort=price
// User clicks "Español"
// Target URL: /es/products?category=shoes&sort=price
If using path-based routing (/en/, /es/), replace the locale segment while keeping everything after it. Preserve the query string exactly:
function buildLocaleUrl(newLocale, currentPath, queryString) {
// Replace locale in path (e.g., /en/products → /es/products)
const newPath = currentPath.replace(/^\/[a-z]{2}\//, `/${newLocale}/`);
return queryString ? `${newPath}?${queryString}` : newPath;
}
The same principle applies to subdomain patterns (en.example.com) or query-based approaches (?lang=en)—just update the locale identifier while keeping the rest.
Key Takeaway: Always reconstruct locale-switch URLs by preserving the current page path and all query parameters, changing only the locale identifier to maintain the user's context and workflow.