To store objects in HTML5 localStorage
or sessionStorage
, follow these steps:
1. Convert the Object to a JSON String
Web Storage (both localStorage
and sessionStorage
) only supports strings. Use JSON.stringify()
to serialize objects into JSON strings.
const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com'
};
// Convert the object to a JSON string
const userJSON = JSON.stringify(user);
2. Store the String in Web Storage
Use setItem(key, value)
to save the JSON string with a unique key.
// Using localStorage
localStorage.setItem('user', userJSON);
// Using sessionStorage (same syntax)
sessionStorage.setItem('user', userJSON);
3. Retrieve and Parse the Data
Fetch the stored string using getItem(key)
, then parse it back to an object with JSON.parse()
.
// Retrieve from localStorage
const storedUserJSON = localStorage.getItem('user');
const storedUser = JSON.parse(storedUserJSON);
// Retrieve from sessionStorage
const sessionUserJSON = sessionStorage.getItem('user');
const sessionUser = JSON.parse(sessionUserJSON);
Example Workflow
// Store an object
const settings = { theme: 'dark', notifications: true };
localStorage.setItem('settings', JSON.stringify(settings));
// Retrieve and use the object
const loadedSettings = JSON.parse(localStorage.getItem('settings'));
console.log(loadedSettings.theme); // Output: 'dark'
Key Notes:
- Data Persistence:
localStorage
: Persists until explicitly deleted (survives browser restarts).sessionStorage
: Cleared when the browser tab/window closes.- Limitations:
- Size Limits: Typically ~5MB per domain.
- Data Types: JSON cannot serialize complex types like
Date
,Function
, or circular references. Handle these manually if needed. - Errors: Wrap
JSON.parse()
in atry-catch
block to handle invalid JSON.
Edge Cases:
- If the stored data is missing,
getItem()
returnsnull
:
const data = JSON.parse(localStorage.getItem('nonExistentKey') || '{}');
- Rehydrate dates or custom types after parsing:
const storedObj = JSON.parse(storedJSON);
storedObj.date = new Date(storedObj.date);
By serializing objects to JSON strings, you can reliably store and retrieve structured data in web storage.