How to set an item in localStorage in JavaScript

Setting items in localStorage allows you to store data persistently in the user’s browser, perfect for saving preferences, form data, or application state. As the creator of CoreUI, a widely used open-source UI library, I’ve used localStorage extensively for theme preferences, sidebar state, and user settings persistence. From my expertise, the localStorage.setItem() method is the standard way to store key-value pairs that persist across browser sessions. This approach provides reliable client-side storage that survives page refreshes and browser restarts.

Use localStorage.setItem() to store data with a key-value pair in browser storage.

localStorage.setItem('username', 'john123')
localStorage.setItem('settings', JSON.stringify({ theme: 'dark', lang: 'en' }))

Here localStorage.setItem() takes two parameters: a key string and a value string. For complex data like objects or arrays, use JSON.stringify() to convert them to strings before storage. The data persists until explicitly removed or the user clears browser data, making it ideal for user preferences and application state.

Best Practice Note:

Always use try-catch blocks as localStorage can throw errors when storage is full or disabled. This is the same approach we use in CoreUI components for reliable theme and preference persistence across user sessions.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author