Why does localStorage only store strings?
Where Web Storage came from, why it's synchronous and small, and why you pack objects yourself.
localStorage — and got the string "1,2" back. I put in an object — and got "[object Object]". No error, no warning. Who stole my data? Opening an investigation.localStorage.setItem("cart", [1, 2]);
localStorage.setItem("cat", {});
localStorage.setItem("empty", null);
localStorage.setItem("nothing", undefined);
console.log(localStorage.getItem("cart"));
console.log(localStorage.getItem("cat"));
console.log(localStorage.getItem("empty"));
console.log(localStorage.getItem("nothing"));null is now the string "null".The thief is found: plain old conversion to a string. setItem does to a value exactly what String(value) does. An array has its own toString — it glues the elements with commas. A plain object has the default one, which returns "[object Object]". There's no error because, as far as the language is concerned, nothing went wrong: you asked for a string, you got a string.
So why can't the store handle objects? The answer is history. Web Storage arrived around 2009 with HTML5, as a replacement for cookies for data that doesn't need to go to the server. Early drafts of the standard allowed almost any value — but browsers only implemented strings, and the standard was eventually rewritten to match.
Strings have honest reasons behind them:
- the data sits on disk and must survive the browser closing — so it has to be turned into bytes anyway;
- every browser version and every version of your site reads a string the same way, while a "live object" with prototypes, functions and dates isn't so easy to save;
- you choose the packing format: JSON, CSV, something of your own.
The second trait: localStorage is synchronous. getItem pauses all JavaScript on the page until it has read the value. For a couple of settings that's instant — but it's also why the store is small, about 5 MB per site. For big data (offline mail, an image cache) there's IndexedDB: it's asynchronous, stores objects without JSON and holds far more.
The third: one origin — protocol + domain + port. https://tasky.dev has its own store, https://evil.example has its own, and a foreign site can't read yours. But all scripts on your page share one store — which is why secrets don't go there.
const data = {
born: new Date(Date.UTC(2020, 0, 1)),
toys: new Set(["mouse"]),
nap: undefined,
};
const text = JSON.stringify(data);
console.log(text);
const back = JSON.parse(text);
console.log(typeof back.born);
console.log(back.toys);
console.log("nap" in back);Set an empty object, and undefined vanished.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.