Back to Explore
GuideVibeFix editorialUpdated Nov 20, 2026

Close the browser, your settings stay: localStorage, explained plainly

The order page remembers a customer's theme, font size, and favorite dishes, so the next visit starts where the last one ended — all with localStorage. This guide follows MDN's Using the Web Storage API, localStorage, and Storage references: strings only, the setItem trio, checking first, JSON conversion, no property access, length and key, localStorage vs sessionStorage, the storage event, availability checks, protocols and file:, SecurityError, and private mode.

Real photo: a person writing in a spiral notebook with a white pen at a wooden desk, a laptop and glasses beside the notebook

First, the boundaries. The site already has “Stop letting requests fail quietly: the Fetch API”, about fetching data from the backend, and “Registration is not the finish line: new-user onboarding”, which uses localStorage in passing to remember a three-step guide — but only that one use. This guide covers neither fetching nor onboarding flows. It covers one thing: localStorage, the small store in the browser that is still there after you close it and open it again — how to save, how to read, and where it goes wrong. The “Greenstone Cafe” below is the same fictional practice project as before: a small web tool that takes orders for a street-corner cafe. This time it is the order page: remembering the theme color, font size, and favorite dishes a customer picked last time, so the next visit does not start from scratch. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. Everything about local storage syntax and behavior comes from three MDN reference pages — “Using the Web Storage API”, “Window: localStorage property”, and “Storage”. The sources are listed in this article's meta information and evidence record. The examples in the docs — the color setting colorSetting, the background color bgcolor, the cat named Tom, the person named Alex — are the docs' own examples, not real services.

Step 1: A small store where keys and values are always strings, and closing the browser does not empty it

localStorage is a small store the browser keeps for each site, holding key-value pairs: one key, one value, as simple as an object, but it survives closing the page and closing the browser and opening it again. MDN puts it plainly: storage objects are simple key-value stores, similar to objects, but they stay intact through page loads; the keys and the values are always strings, and integer keys will be automatically converted to strings. Saving something in localStorage means putting a small note in that store, and the note can only hold writing — not an object, a number, or an array directly. To store anything else, convert it to a string first; step 4 covers that in detail. The cafe order page remembers preferences this way: a customer picks a dark theme, the page writes the key "theme" with the value "dark", and on the next visit it looks in the store first and applies the dark theme without asking again. Remember the first sentence: localStorage is a per-site store of strings, and closing the browser leaves it in place.

Step 2: Three tools plus one clear-out — setItem, getItem, removeItem, clear

Putting things in, taking things out, and throwing things away takes four methods. MDN's Storage page states them cleanly: setItem() takes a key name and a value, and adds that key or updates its value if it already exists; getItem() takes a key name and returns that key's value; removeItem() takes a key name and removes that key from the storage object; clear() takes no arguments and empties the entire storage object. The localStorage page shows the minimal form of all four: localStorage.setItem("myCat", "Tom") stores a cat named Tom, const cat = localStorage.getItem("myCat") reads it back, localStorage.removeItem("myCat") deletes it, and localStorage.clear() empties the store. The cafe order page remembers the theme the same way: localStorage.setItem("theme", "dark") writes it, localStorage.getItem("theme") reads it on the next visit, and when the customer clicks “restore defaults” it calls localStorage.removeItem("theme") to delete just that one entry — not the whole store, because clear() throws every key away at once. Deleting one entry and emptying everything are different jobs. Remember the rule: save with setItem, read with getItem, delete one entry with removeItem, and empty the whole store only with clear.

Think before deleting: removeItem deletes one key, clear empties the whole store, and neither can be undone — check first whether another page is still using that key. The cafe order page once called clear by mistake inside “restore defaults” and wiped the customer's saved favorites; it now deletes only the theme entry.

Step 3: When a key is not there, check first before going on

Reading a key that was never stored returns an empty value, and MDN's example uses exactly that to test whether anything is stored: if (!localStorage.getItem("bgcolor")), then call populateStorage() to write the defaults first; otherwise call setStyles() and use the stored values to update the page styling. So checking first is the first gate of writing localStorage code. The cafe order page skipped it early on: for a first-time customer there was no "theme" in the store, the code took the value it read and built the styles from it, and the styles came out undefined and the page went blank. After the fix it checks first — nothing stored means write the default "light" before going on. Remember the rule: before getItem, ask “is it there”, and if it is not, write the default first.

Step 4: Strings only — turn objects into strings before saving them

This is the easiest localStorage pitfall, and MDN explains it with a full counter-example. Storage only supports storing and retrieving strings; to save other data types, convert them to strings, and for plain objects and arrays you can use JSON.stringify(). The counter-example goes like this: const person = { name: "Alex" }, then localStorage.setItem("user", person) directly, and localStorage.getItem("user") comes back as "[object Object]" — not useful. The right way is localStorage.setItem("user", JSON.stringify(person)), and on reading, JSON.parse(localStorage.getItem("user")), which returns { name: "Alex" }. MDN adds two more sentences: there is no generic way to store arbitrary data types, and the retrieved object is a deep copy of the original object, so mutations to it do not affect the original object. The cafe order page tripped here: the favorites list is an array, it was stored with a plain setItem, and it came back as "[object Object]" and the favorites section on the page went empty. Storing with JSON.stringify first and parsing with JSON.parse on read brought the array back intact. Remember the rule: before saving, ask “is this a string”, and if it is not, JSON.stringify it first.

Step 5: Do not use property access — use the setItem family

MDN gives a clear warning: always use the Web Storage API — setItem(), getItem(), removeItem(), key, length — instead of direct object property access such as localStorage.key = value or localStorage["key"] = value. The docs list three reasons: property names can collide with native built-in methods, like .clear() or .getItem(); unexpected data leaks can come from prototype inheritance; and handling untrusted user input can bring security vulnerabilities like prototype pollution. Three lines — localStorage.colorSetting = "#a4509b", localStorage["colorSetting"] = "#a4509b", and localStorage.setItem("colorSetting", "#a4509b") — all set the same entry, but only the third is the way MDN recommends. The cafe order page once stored a key called "length" with property access, and what came back was not the stored value but the number of entries in the store — the key name had collided with the built-in length property. After switching to setItem, no key name, however odd, can collide with a built-in method. Remember the rule: save and read only through setItem and getItem; never write properties directly onto the localStorage object.

Step 6: Count the entries and take key names by number — length and key()

Besides saving, reading, and deleting, the Storage interface offers two methods for taking stock of the store. length is read-only and returns an integer representing the number of data items stored in the Storage object; key() takes a number n and returns the name of the nth key in the storage. MDN's Using page notes that you can also use Storage.length to test whether the storage object is empty or not. The cafe order page uses both on its “my preferences” screen: it first checks whether localStorage.length is 0, and if so shows “no preferences stored yet”; otherwise it uses key(i) to list the key names one by one so the customer can pick which one to delete. Remember the rule: to count the store, look at length; to list the key names, use key(n).

Step 7: localStorage and sessionStorage — do not mix them up

Web Storage has two mechanisms. The names look alike and the usage is the same, but the lifetime and the sharing range differ. MDN's wording: sessionStorage maintains a separate storage area for each given origin that is available for the duration of the page session — as long as the browser is open, including page reloads and restores — while localStorage does the same thing, but persists even when the browser is closed and reopened. The two are reached through Window.sessionStorage and Window.localStorage, returning two different Storage objects that are manipulated the same way but separately. The sharing range differs too: for localStorage, the storage space is shared between all tabs with the same origin; for sessionStorage, the storage space is only shared within the tab, among all iframes from the same origin. The cafe order page first stored the theme in sessionStorage, and when customers closed the browser and came back, the theme had reset to the default — preferences that have to survive to the next visit belong in localStorage. The other way around, the dishes being picked during an order in progress should be forgotten when the page closes, so sessionStorage fits them better. Remember the rule: to keep it until the next visit, use localStorage; to keep it only for this session, use sessionStorage.

Step 8: The storage event only fires in other tabs — this page will not hear it

When the store changes, the browser fires a storage event, but with a counter-intuitive rule: it fires only in other documents that share the same storage space, not on the page that is making the change. MDN's wording: the storage event is fired whenever a change is made to the Storage object of another document that shares the same storage space; this won't work on the same page that is making the changes — it is really a way for other pages on the origin using the storage to sync any changes that are made. The event object carries the details of the change: key, the key of the data that changed; oldValue, the value before the change; newValue, the value after the change; url, the URL of the document that changed the storage; and storageArea, the storage object itself. MDN's example listens for the storage event on window and writes those properties to an event output page. The cafe order page uses this for multi-tab sync: a customer changes the theme in one tab, another tab with the order page open receives the storage event and switches theme at once — but the tab that made the change never receives the event, because its theme was switched at the moment of setItem and does not need to wait for the event. Remember the rule: to sync with the storage event, wait in the other tabs; the page making the change handles it on the spot.

Step 9: Test first whether the store can actually be used

Being able to call localStorage is not the same as being able to use it. MDN warns: browsers that support localStorage have a property on the window object named localStorage, but just testing that the property exists may be insufficient — various browsers offer settings that disable the storage API without hiding the global object, and in a browser's private browsing mode some browsers might give an empty localStorage object with a quota of zero, effectively making it unusable. The other way around, a legitimate QuotaExceededError means all available storage space has been used up, but storage is actually available. MDN provides a ready-made detection function, storageAvailable(type): try writing a test entry and removing it, and return true if that works; if it throws, return true only when the error is a DOMException named QuotaExceededError and there is already something stored (storage.length is not 0), otherwise false. It is used as if (storageAvailable("localStorage")) — go on only when it can be used, and take the fallback path when it cannot. The cafe order page calls this check first: in private mode the check fails, so preferences are kept only in memory — usable for this session, forgotten when it closes — and the page never throws an error. Remember the rule: try a test write and delete first, then decide whether to put things in the store.

Step 10: http and https are two different stores, and pages opened from a file should not rely on it

localStorage is divided by origin, and the origin includes the protocol. MDN says so plainly on the localStorage page: localStorage data is specific to the protocol of the document — a site loaded over HTTP returns a different object than the same site loaded over HTTPS. And for documents loaded from file: URLs — files opened in the browser directly from the local filesystem rather than being served from a web server — the requirements for localStorage behavior are undefined and may vary among different browsers. In all current browsers it seems to return a different object for each file: URL, but there are no guarantees about that behavior, so you should not rely on it, because the requirements for file: URLs remain undefined and browsers may change their handling at any time — in fact some browsers have changed their handling over time. Someone on the cafe order page once double-clicked the HTML file to open it in the browser: the theme was stored, and opening it in another browser it was gone — the undefined behavior of file: URLs at work. Remember the rule: always test localStorage through an http or https server, never by double-clicking a file.

Step 11: When it cannot be saved, here is how the browser refuses

Reading localStorage can throw a SecurityError, and MDN lists two cases. The first is that the origin is not a valid scheme/host/port tuple — this can happen if the origin uses the file: or data: schemes, for example. The second is that the request violates a policy decision — for example, the user has configured the browser to prevent the page from persisting data. MDN adds that if the user blocks cookies, browsers will probably interpret this as an instruction to prevent the page from persisting data. The cafe order page ran into this when a customer's browser had strict privacy settings: reading localStorage threw, and the page went blank. After wrapping the localStorage reads in try/catch, a throw falls back to the in-memory plan and the page keeps working. Remember the rule: reading localStorage can throw too, so wrap the important reads in try/catch and never let one failed read take the whole page down.

Step 12: Set a rule for key names before they get messy

This step is not from MDN — it is a rule for your own team — but it saves a lot of trouble later. Give key names a project prefix and a version number, such as "cafe:theme:v1" and "cafe:favorites:v1", for three reasons: first, different features cannot collide on key names; second, when the data format changes, bumping the version makes old data recognizable at a glance, so it can be handled in the old format or cleared; third, opening developer tools during debugging shows at a glance which keys belong to this project. The cafe order page started with bare key names, "theme" and "favorites", and later a small third-party widget also wrote a "theme" into localStorage — the two overwrote each other, and customers' themes changed three times a day. After the "cafe:" prefix, collisions stopped. Remember the rule: put a project prefix and a version number on key names, and save yourself the later reconciliation.

Step 13: In private mode, it only lives until the last private tab closes

localStorage has one easily missed exception, and MDN states it plainly on the localStorage page: localStorage data for a document loaded in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed. Ordinary localStorage has no expiration time — close the browser and open it again and it is still there. But the copy in private mode only lives until the last private tab closes. The cafe order page once got feedback from a customer about exactly this: a theme picked in a private window was gone when the window was closed and reopened, and the customer thought the page was broken. The page was not broken — that is simply the rule in private mode, and closing the last private tab clears the data. Remember the rule: in private mode, do not count on localStorage keeping things for long; it only lives until the last private tab closes.

Step 14: Save as soon as the form changes — do not wait for submit

Preferences do not need to wait for the customer to click “save” before they are written to the store — they can be saved the moment a form value changes. MDN's Web Storage Demo works exactly this way: each form element has an onchange handler, bgcolorForm.onchange = populateStorage, fontForm.onchange = populateStorage, imageForm.onchange = populateStorage, so a change calls populateStorage(), writes the three values into localStorage, and then calls setStyles() to update the page styling. The benefit is that a customer can change something and leave, and on refresh everything they changed is still there — nothing is lost for want of a save click. The cafe order page remembers theme and font size this way: change the dropdown, and the value is written to the store and the page changes at once. The customer never has to look for a save button, and never loses a setting by forgetting to save. Remember the rule: write a preference to the store as soon as it changes; do not wait for the submit button.

The version number has one more use: when the data format changes, old-version data read back can be handled in the old format, or cleared and rewritten, instead of leaving new code to guess what old data looks like. When the cafe order page changed favorites from storing just names to storing names plus prices, the v1 to v2 bump recognized the old data and quietly cleared and rewrote it, and customers never noticed a thing.

Bar chart of 70 local storage incidents in one month, by cause

Checklist: run through this list when your localStorage is written

The chart below shows the causes of 70 local storage incidents in one month on the fictional Greenstone Cafe order page: storing an object directly without stringify and reading back "[object Object]", 21 times (30.0%); calling JSON.parse straight on a getItem that returned nothing, and the empty value blowing up, 14 times (20.0%); property access colliding with a built-in method name, 11 times (15.7%); using sessionStorage as if it were localStorage, and losing everything when the browser closed, 9 times (12.9%); waiting for the storage event in the wrong place, so the same page never heard the sync, 8 times (11.4%); opening the page by double-clicking a file:, where storage behavior differs between browsers, 7 times (10.0%). 21 + 14 + 11 + 9 + 8 + 7 = 70, and the percentages add up to 100.0%. The numbers are invented examples; the lessons are real, and the largest category is exactly the most basic rule of localStorage — strings only. When your own localStorage is written, run through this list: before saving, ask “is this a string”, and if it is not, JSON.stringify first; before reading, check for empty, and write the default first when nothing is there; save and read only through setItem and getItem, never by writing properties directly onto the object; check whether localStorage and sessionStorage are mixed up — keep-until-next-visit versus keep-only-this-session; when waiting for the storage event to sync, are you waiting in the right tab; test first whether the store can be used, and is there a fallback for private mode; are you testing through an http or https server rather than double-clicking a file; are the important localStorage reads wrapped in try/catch; and do the key names carry a project prefix and a version number; and in private mode, are you counting on it keeping things for long; and are form changes saved at once, without waiting for submit. When all eleven pass, the local storage is done.

Views 1Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: a bank of light gray metal filing cabinets with one drawer pulled open, revealing rows of hanging file folders inside
Guide
A real database inside the browser: IndexedDB local storage, explained plainly

localStorage only stores strings and has no indexes. IndexedDB is a real database in the browser: structured data, far larger capacity, indexes, and transactions. Following MDN's Using IndexedDB, IDBDatabase, and IDBObjectStore: the five-step routine, opening, upgrades, keys, indexes, transactions, add versus put, get, cursors, ranges, and multi-tab upgrades.

Tool TipsData WorkflowsFrontend Engineering
Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a laptop, tablet, and phone on a wooden table showing the same green-leaf website, the phone view with navigation in one column, a potted plant nearby
Guide
Squashed on phones? Responsive layout and media queries, explained plainly

One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.

Mobile AppsDesign ExperienceFrontend Engineering