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

localStorage for Locale Preference

Use localStorage to remember user-selected locale without server-side storage requirements.

localStorage for Locale Preference

What you'll learn: How to use localStorage to remember a user's chosen language or region without needing a server or database.

The Core Idea

When a user selects their preferred locale (like "en-US" or "es-MX"), you want that choice to persist across page reloads and visits—but you don't always have a backend or user account system to save it. That's where localStorage shines. It's a client-side key-value store built into every modern browser that keeps data around indefinitely until explicitly cleared.

Think of localStorage like a sticky note attached to the user's browser. Whatever you write there stays put, even after they close the tab or restart their computer.

How It Works

When the user picks a locale, store it:

// User selects "fr-FR" from a language picker
localStorage.setItem('userLocale', 'fr-FR');

On subsequent page loads, retrieve it:

const savedLocale = localStorage.getItem('userLocale');
const locale = savedLocale || navigator.language || 'en-US'; // fallback chain
console.log('Using locale:', locale);

To remove it (say, when user logs out or resets):

localStorage.removeItem('userLocale');

Why It Beats Cookies Here

Unlike cookies, localStorage doesn't get sent with every HTTP request, saving bandwidth. It also offers more storage space (typically 5-10MB vs 4KB per cookie) and a simpler API for this use case.

The Tradeoff

This is purely client-side—if the user switches devices or browsers, they'll need to select their locale again. It's not shared across domains either. But for most single-domain web apps without authentication, it's the perfect lightweight solution.

Key Takeaway: Use localStorage.setItem() and getItem() to persist locale preference entirely in the browser, eliminating server-side storage complexity while keeping user experience smooth across sessions.