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.
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};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.
No. Any JavaScript running on the page can read localStorage. Never store tokens, passwords, or PII there.
Typically 5 MB per origin in most browsers, though this varies. Exceeding it throws a QuotaExceededError.
localStorage persists across browser sessions. sessionStorage is cleared when the browser tab is closed.
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.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.