How to Store (and Retrieve) a JavaScript Object in localStorage

📋 What You’ll Learn

  • What localStorage is and when to use it
  • Why you must serialize objects before saving
  • Step-by-step code for saving, reading and removing an object
  • Common gotchas and tips

1. What Is localStorage?

  • A simple key–value store built into every modern browser
  • Persists data across page reloads and browser restarts
  • Synchronous API (blocks briefly while reading/writing)
  • Stores only strings — not numbers, objects or arrays directly
MethodWhat it does
setItem(key, value)Save a string under key
getItem(key)Retrieve string for key (or null)
removeItem(key)Delete entry for key
clear()Wipe all keys in this origin

2. Why JSON.stringify / JSON.parse?

Since localStorage only holds strings, to store an object you must:

  1. Serialize it into a string: jsCopyEditconst json = JSON.stringify(myObject);
  2. Deserialize it back into an object: jsCopyEditconst obj = JSON.parse(jsonString);

3. Step-by-Step Example

Let’s say you have a user-profile object:

const userProfile = {
id: 42,
name: "Alex",
prefs: { theme: "dark", fontSize: 16 }
};

a) Save to localStorage

function saveProfile(profile) {
// 1. Convert object → JSON string
const json = JSON.stringify(profile);

// 2. Store under key "userProfile"
localStorage.setItem("userProfile", json);
}

b) Read back from localStorage

function loadProfile() {
const json = localStorage.getItem("userProfile");
if (!json) {
console.warn("No profile found in localStorage.");
return null;
}

// Convert JSON string → object
try {
return JSON.parse(json);
} catch (err) {
console.error("Failed to parse profile JSON:", err);
return null;
}
}

c) Remove it when you’re done

function clearProfile() {
localStorage.removeItem("userProfile");
}

4. Full Demo Code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>localStorage Object Demo</title>
</head>
<body>
<button id="save">Save Profile</button>
<button id="load">Load Profile</button>
<button id="clear">Clear Profile</button>
<pre id="output"></pre>

<script>
const userProfile = {
id: 42,
name: "Alex",
prefs: { theme: "dark", fontSize: 16 }
};

document.getElementById("save").addEventListener("click", () => {
localStorage.setItem("userProfile", JSON.stringify(userProfile));
document.getElementById("output").textContent = "Profile saved.";
});

document.getElementById("load").addEventListener("click", () => {
const json = localStorage.getItem("userProfile");
if (json) {
const profile = JSON.parse(json);
document.getElementById("output").textContent =
`Loaded profile:\n${JSON.stringify(profile, null, 2)}`;
} else {
document.getElementById("output").textContent = "No profile found.";
}
});

document.getElementById("clear").addEventListener("click", () => {
localStorage.removeItem("userProfile");
document.getElementById("output").textContent = "Profile cleared.";
});
</script>
</body>
</html>

5. Checklist & Best Practices

  • Always JSON.stringify before saving non-string data
  • Wrap JSON.parse in try/catch to handle corruption
  • Clean up with removeItem when data is stale
  • Don’t store sensitive info (localStorage is readable by any JS on your domain)
  • Keep stored objects small (5–10 MB quota varies by browser)

🚀 Next Steps

  • Extend to store an array of profiles
  • Fallback to cookies or IndexedDB for larger or more secure data
  • Use a wrapper library (e.g. store.js) for cross-browser quirks

With this pattern you can persist user settings, caches or small state-snapshots between sessions—without any server round-trips!