Cookie-Based Locale Persistence
What you'll learn: How to save a user's language preference in a cookie so their choice persists across browser sessions and page visits.
The Core Idea
After detecting or allowing a user to select their preferred locale (through navigator.language, URL patterns, or an explicit selector), you need a way to remember that choice. Cookies provide a simple, reliable mechanism to store this preference on the client side and send it with every request, ensuring consistency across sessions.
Think of cookies as sticky notes that your browser attaches to every conversation with a website. When a user chooses "Spanish" as their language, you write that down on a sticky note (cookie). Every time they return—even days later—that note is still there, telling your server, "This person prefers Spanish."
How It Works
When a user selects or you detect their locale:
// Set a locale cookie (expires in 1 year)
document.cookie = "user_locale=es-MX; max-age=31536000; path=/; SameSite=Lax";
To retrieve it later:
function getLocaleCookie() {
const match = document.cookie.match(/user_locale=([^;]+)/);
return match ? match[1] : null;
}
const savedLocale = getLocaleCookie(); // "es-MX"
Server-side frameworks can read this cookie from request headers and serve localized content immediately, without JavaScript execution delays.
Cookie vs Other Storage
Unlike localStorage, cookies travel with HTTP requests, making them ideal for server-side rendering. They work across subdomains (when configured) and survive browser restarts. Set appropriate max-age, path, and SameSite attributes for security and longevity.
Key Takeaway: Cookies provide persistent, cross-session locale storage that both client and server can access, ensuring users see their preferred language automatically on every visit.