Logo

How to store objects in HTML5 localStorage/sessionStorage?

HTML5 localStorage and sessionStorage can only store strings, so you need to convert objects to JSON before saving, and parse them back when retrieving. Below is a step-by-step guide:

1. Storing Objects

Use JSON.stringify() to serialize your object into a JSON string, which you can then store in either localStorage (persistent across sessions) or sessionStorage (cleared when the browser tab closes):

const user = { name: "Alice", age: 25, preferences: { theme: "dark", notifications: true } }; // Store object in localStorage localStorage.setItem("user", JSON.stringify(user)); // Store object in sessionStorage sessionStorage.setItem("user", JSON.stringify(user));

When to Use localStorage vs. sessionStorage

  • localStorage: Data persists even after the browser or tab is closed (until explicitly cleared).
  • sessionStorage: Data persists only for the session (i.e., until the tab or browser is closed).

2. Retrieving Objects

When reading objects back from storage, parse the JSON string using JSON.parse():

const storedUserStr = localStorage.getItem("user"); if (storedUserStr) { const storedUser = JSON.parse(storedUserStr); console.log(storedUser.name); // "Alice" }

3. Best Practices

  1. Check for null: getItem() returns null if the key is missing. Always verify before parsing.
  2. Use a try-catch (optional) in case of malformed data:
    try { const data = JSON.parse(localStorage.getItem("user")); } catch (err) { console.error("Error parsing JSON from storage", err); }
  3. Remember storage limits: Browsers usually allow around 5–10 MB per domain for localStorage/sessionStorage.
  4. Avoid storing sensitive data: Data in localStorage/sessionStorage is easily accessible to client-side scripts; never store passwords or secrets there.

Level Up Your JavaScript Skills

If you want a deeper understanding of JavaScript fundamentals—including DOM manipulation, asynchronous patterns, and storage APIs—explore these courses on DesignGurus.io:

For more tutorials on coding best practices and system design insights, visit the DesignGurus.io YouTube channel. This combination of knowledge ensures you’ll use localStorage/sessionStorage efficiently and securely in real-world applications.

CONTRIBUTOR
TechGrind