How to store objects in HTML5 localStorage/sessionStorage
Categories:
Mastering Web Storage: Storing Objects in localStorage and sessionStorage

Learn how to effectively store and retrieve complex JavaScript objects in HTML5's localStorage and sessionStorage, overcoming their string-only limitation.
HTML5's localStorage
and sessionStorage
provide a convenient way to store key-value pairs directly within the user's browser. This client-side storage mechanism is incredibly useful for persisting user preferences, caching data, or maintaining application state across sessions or page reloads. However, a common challenge arises when developers need to store complex JavaScript objects, as both localStorage
and sessionStorage
inherently only support storing strings.
The String-Only Limitation and Its Solution
The core limitation of localStorage
and sessionStorage
is that they can only store data as strings. If you try to store a JavaScript object directly, it will be implicitly converted to its string representation, which often results in [object Object]
â a useless value for retrieval. The solution to this problem lies in using JSON (JavaScript Object Notation) to serialize objects into strings before storing them, and then parsing them back into objects upon retrieval.
flowchart TD A[JavaScript Object] --> B{"JSON.stringify()"} B --> C[JSON String] C --> D[localStorage/sessionStorage.setItem()] D --> E[Web Storage] E --> F[localStorage/sessionStorage.getItem()] F --> G[JSON String] G --> H{"JSON.parse()"} H --> I[JavaScript Object]
Process of storing and retrieving JavaScript objects in web storage
Storing Objects in localStorage
localStorage
allows you to store data with no expiration date. The data remains available even after the browser window is closed and reopened. To store an object, you first convert it to a JSON string using JSON.stringify()
, then use localStorage.setItem()
to save it. When retrieving, you use localStorage.getItem()
and then JSON.parse()
to convert the JSON string back into a JavaScript object.
// 1. Define a JavaScript object
const userSettings = {
theme: 'dark',
fontSize: 16,
notifications: true,
lastLogin: new Date()
};
// 2. Convert the object to a JSON string
const userSettingsJSON = JSON.stringify(userSettings);
// 3. Store the JSON string in localStorage
localStorage.setItem('myUserSettings', userSettingsJSON);
console.log('Object stored in localStorage:', userSettingsJSON);
// 1. Retrieve the JSON string from localStorage
const storedSettingsJSON = localStorage.getItem('myUserSettings');
// 2. Convert the JSON string back to a JavaScript object
const retrievedSettings = JSON.parse(storedSettingsJSON);
console.log('Object retrieved from localStorage:', retrievedSettings);
console.log('Theme:', retrievedSettings.theme);
console.log('Font Size:', retrievedSettings.fontSize);
JSON.stringify()
will convert Date
objects into ISO 8601 strings. When you JSON.parse()
them back, they will remain strings. If you need them as Date
objects, you'll have to manually convert them after parsing.Storing Objects in sessionStorage
sessionStorage
works identically to localStorage
in terms of API and the string-only limitation, but with a crucial difference: the data stored in sessionStorage
is cleared when the browser tab or window is closed. This makes it ideal for storing temporary, session-specific data that doesn't need to persist across browser sessions.
// 1. Define a session-specific object
const sessionData = {
cartId: 'abc123xyz',
items: [{ id: 1, qty: 2 }, { id: 3, qty: 1 }],
timestamp: Date.now()
};
// 2. Convert the object to a JSON string
const sessionDataJSON = JSON.stringify(sessionData);
// 3. Store the JSON string in sessionStorage
sessionStorage.setItem('currentSessionData', sessionDataJSON);
console.log('Object stored in sessionStorage:', sessionDataJSON);
// 1. Retrieve the JSON string from sessionStorage
const storedSessionJSON = sessionStorage.getItem('currentSessionData');
// 2. Convert the JSON string back to a JavaScript object
const retrievedSessionData = JSON.parse(storedSessionJSON);
console.log('Object retrieved from sessionStorage:', retrievedSessionData);
console.log('Cart ID:', retrievedSessionData.cartId);
localStorage.getItem()
or sessionStorage.getItem()
might return null
(if the key doesn't exist). Attempting to JSON.parse(null)
will work, but JSON.parse(undefined)
will throw an error. It's good practice to check for null
before parsing.Error Handling and Best Practices
When working with web storage, it's important to consider potential errors and best practices to ensure robust applications. This includes handling cases where storage might be full, or when parsing invalid JSON.
function saveObjectToLocalStorage(key, obj) {
try {
const jsonString = JSON.stringify(obj);
localStorage.setItem(key, jsonString);
return true;
} catch (e) {
console.error(`Error saving object to localStorage for key "${key}":`, e);
// Handle QuotaExceededError (storage full) or other serialization errors
return false;
}
}
function getObjectFromLocalStorage(key) {
try {
const jsonString = localStorage.getItem(key);
if (jsonString === null) {
return null; // Key does not exist
}
return JSON.parse(jsonString);
} catch (e) {
console.error(`Error retrieving or parsing object from localStorage for key "${key}":`, e);
// Handle JSON parsing errors or other retrieval issues
return null;
}
}
// Example usage:
const myData = { name: 'Alice', age: 30 };
saveObjectToLocalStorage('userData', myData);
const retrievedData = getObjectFromLocalStorage('userData');
console.log('Retrieved data with error handling:', retrievedData);