Back to all snippets
Library/JavaScript/Local Storage Helper
javascriptintermediatestorageutilitiesbrowser

How to implement Local Storage Helper in Javascript

Type-safe localStorage wrapper with JSON support and error handling

Quick Answer

Wrap localStorage with helper methods that automatically JSON-serialise values and catch storage errors, giving you a clean, safe API for browser-side persistence.

Code Snippet

1const storage = {
2  set: (key, value) => {
3    try {
4      localStorage.setItem(key, JSON.stringify(value));
5    } catch (e) {
6      console.error('Error saving to localStorage', e);
7    }
8  },
9  get: (key, defaultValue = null) => {
10    try {
11      const item = localStorage.getItem(key);
12      return item ? JSON.parse(item) : defaultValue;
13    } catch (e) {
14      console.error('Error reading from localStorage', e);
15      return defaultValue;
16    }
17  },
18  remove: (key) => localStorage.removeItem(key),
19  clear: () => localStorage.clear()
20};

What is Local Storage Helper?

This localStorage helper provides a clean API for storing and retrieving data from browser storage with automatic JSON serialisation. It includes error handling for quota exceeded errors and invalid JSON, making it production-ready and reliable.

How It Works

  1. 1storage.set stringifies the value before calling setItem.
  2. 2A try/catch handles QuotaExceededError and other storage exceptions.
  3. 3storage.get parses the stored string back to its original type.
  4. 4A defaultValue is returned if the key does not exist or the JSON is malformed.
  5. 5storage.remove and storage.clear delegate directly to the native API.

Common Use Cases

  • User preferences — save theme, language, and settings
  • Form data — persist form inputs between sessions
  • Shopping carts — store cart items locally
  • Cache — store API responses for offline access

Key Benefits

  • Automatic JSON serialisation and deserialisation
  • Built-in error handling
  • Clean API over raw localStorage
  • Safe default value fallback

Common Mistakes to Avoid

  • Not wrapping reads in try/catch — stored JSON can be corrupted between sessions.
  • Storing sensitive data in localStorage — it is accessible to any script on the page.
  • Forgetting that localStorage is synchronous and can block the main thread for large payloads.
  • Calling localStorage in server-side rendering contexts where window is undefined.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more javascript examples

Frequently Asked Questions

Is localStorage safe for sensitive data?

No. Any JavaScript running on the page can read localStorage. Never store tokens, passwords, or PII there.

What is the localStorage size limit?

Typically 5 MB per origin in most browsers, though this varies. Exceeding it throws a QuotaExceededError.

How is localStorage different from sessionStorage?

localStorage persists across browser sessions. sessionStorage is cleared when the browser tab is closed.

About This Javascript Code Snippet

This free javascript code snippet for local storage helper is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement local storage helper quickly and correctly.

All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.

Tags: storage, utilities, browser  | Language: javascript  | Difficulty: intermediate  | Category: JavaScript

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.