How to get an item from localStorage in JavaScript

Getting items from localStorage allows you to retrieve previously stored data, enabling persistent user experiences across browser sessions. As the creator of CoreUI, a widely used open-source UI library, I’ve used localStorage retrieval extensively for restoring user themes, sidebar states, and personalized settings. From my expertise, the localStorage.getItem() method is the standard way to access stored data using its key. This approach provides reliable access to persistent client-side data that maintains user preferences and application state.

Use localStorage.getItem() to retrieve stored data by its key from browser storage.

const username = localStorage.getItem('username')
const settings = JSON.parse(localStorage.getItem('settings') || '{}')

Here localStorage.getItem('username') retrieves the value associated with the ‘username’ key, returning null if the key doesn’t exist. For complex data stored as JSON strings, use JSON.parse() to convert back to objects. Always provide fallback values using the OR operator to handle missing keys gracefully.

Best Practice Note:

Always check for null values and use fallbacks since getItem() returns null for non-existent keys. This is the same approach we use in CoreUI components for robust data retrieval and graceful handling of missing user preferences.


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

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to force a React component to re-render
How to force a React component to re-render

How to convert a string to boolean in JavaScript
How to convert a string to boolean in JavaScript

CSS Selector for Parent Element
CSS Selector for Parent Element

How to Center a Button in CSS
How to Center a Button in CSS

Answers by CoreUI Core Team