localStorage: saving data in the browser
Remember preferences and lists with localStorage, JSON and safe helper functions.
In this lesson you will
- Save and load values with localStorage
- Store objects and arrays with JSON
- Write safe load and save helpers
- Know what not to store
About 17 minutes
A page that remembers you
You switch a site to dark mode, close the tab, and come back tomorrow. It is still dark. Or you add three items to a shopping basket and refresh the page, and they are still there. Something is remembering. For many sites, that something is web storage, a small box of data that the browser keeps for each website, right on the visitor’s device. No server, no account, no database needed.
localStorage basics
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
console.log(theme); // "dark"
localStorage.removeItem("theme");
localStorage.clear(); // remove everything for this site
console.log(localStorage.getItem("missing")); // null
setItem(key, value)saves a value under a name.getItem(key)reads it back, ornullif missing.removeItem(key)deletes one entry.clear()deletes all entries for the site.
Values are always stored as text. The number 5 comes back as "5", so convert with Number() when you read it.
Storing objects and arrays with JSON
const settings = { theme: "dark", fontSize: 18, favourites: ["css", "js"] };
localStorage.setItem("settings", JSON.stringify(settings));
const saved = JSON.parse(localStorage.getItem("settings"));
console.log(saved.favourites[1]); // "js"
You met JSON.stringify and JSON.parse in the objects lesson. Here they earn their keep: they turn any object or array into text and back. Always handle the “nothing saved yet” case.
function load(key, fallback) {
try {
const raw = localStorage.getItem(key);
return raw === null ? fallback : JSON.parse(raw);
} catch (err) {
return fallback; // corrupt data or storage blocked
}
}
function save(key, value) {
try { localStorage.setItem(key, JSON.stringify(value)); }
catch (err) { console.warn("Could not save", err); }
}
let todos = load("todos", []);
In the live editors on this page, the preview runs in a sandboxed frame where the browser blocks real storage. The editors below use a small stand-in object that behaves the same way, so you can practise the exact code. On your own site and in your own files, plain localStorage works as shown.
Save the typed name when you press Save, and show the saved name when the page loads. Press Save, then use Reset in the editor header and see how the stand-in remembers within the page.
<style>body{font-family:Arial;padding:14px} input,button{padding:9px;font-size:15px} button{background:#5A28C8;color:#fff;border:0;border-radius:8px}</style>
<input id="n" placeholder="Your name">
<button id="save">Save</button>
<p id="out"></p>
<script>
// stand-in for sandboxed preview: behaves like localStorage
let store;
try { localStorage.setItem('t', '1'); localStorage.removeItem('t'); store = localStorage; }
catch (e) { const m = {}; store = { getItem: k => (k in m ? m[k] : null), setItem: (k, v) => { m[k] = String(v); } }; }
const n = document.getElementById('n');
const out = document.getElementById('out');
const saved = store.getItem('name');
out.textContent = saved ? 'Welcome back, ' + saved : 'Hello, stranger';
// on Save click: store the name with setItem and update out
</script>
document.getElementById(‘save’).addEventListener(‘click’, () => { store.setItem(‘name’, n.value); out.textContent = ‘Saved ‘ + n.value; });
<style>body{font-family:Arial;padding:14px} input,button{padding:9px;font-size:15px} button{background:#5A28C8;color:#fff;border:0;border-radius:8px}</style>
<input id="n" placeholder="Your name">
<button id="save">Save</button>
<p id="out"></p>
<script>
// stand-in for sandboxed preview: behaves like localStorage
let store;
try { localStorage.setItem('t', '1'); localStorage.removeItem('t'); store = localStorage; }
catch (e) { const m = {}; store = { getItem: k => (k in m ? m[k] : null), setItem: (k, v) => { m[k] = String(v); } }; }
const n = document.getElementById('n');
const out = document.getElementById('out');
const saved = store.getItem('name');
out.textContent = saved ? 'Welcome back, ' + saved : 'Hello, stranger';
document.getElementById('save').addEventListener('click', function () {
store.setItem('name', n.value);
out.textContent = 'Saved ' + n.value;
});
</script>
sessionStorage and cookies
| Feature | Lasts | Size | Sent to server? |
|---|---|---|---|
localStorage |
Until you clear it | About 5 MB | No |
sessionStorage |
Until the tab closes | About 5 MB | No |
| Cookies | Until their expiry date | About 4 KB | Yes, with every request |
| IndexedDB | Until cleared | Hundreds of MB | No |
Use localStorage for preferences and small saved data, sessionStorage for things that should vanish with the tab, and cookies when the server needs the value too, such as a login session. IndexedDB is a full in-browser database for large amounts of data.
A theme that remembers
const saved = localStorage.getItem("theme");
if (saved) document.documentElement.dataset.theme = saved;
document.querySelector("#toggle").addEventListener("click", () => {
const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
document.documentElement.dataset.theme = next;
localStorage.setItem("theme", next);
});
Put the read part as early as possible, so visitors do not see a flash of the wrong theme before your script runs.
Syncing between tabs
window.addEventListener("storage", (e) => {
console.log(e.key, "changed from", e.oldValue, "to", e.newValue);
});
Privacy and safety
- Never store passwords or secrets. Anyone with access to the device, or any script on your page, can read localStorage.
- Treat it as untrusted input. Visitors can edit it in developer tools, so check what you read back.
- Respect privacy rules. Storing anything that identifies a person may need consent in some countries.
- Expect it to disappear. Visitors clear data, private windows discard it, and storage may be blocked. Always have a fallback.
Saving an array or object directly: localStorage.setItem("list", [1,2,3]) stores the text "1,2,3", and an object becomes "[object Object]". Always use JSON.stringify and JSON.parse.
Store a version number with your data, such as { v: 1, items: [...] }. When you change the structure later, you can detect old saves and upgrade them instead of breaking.
Practice: a persistent counter
A visit counter is the smallest useful storage program: read the old number, add one, save it, show it. The only wrinkle is the conversion, because storage hands you text back.
Count how many times the Add button is pressed and keep the total in storage. Show the number on screen. Convert with Number() when reading.
<style>body{font-family:Arial;padding:14px;text-align:center} #n{font-size:56px;font-weight:800;color:#5A28C8} button{padding:10px 18px;background:#5A28C8;color:#fff;border:0;border-radius:8px}</style>
<div id="n">0</div>
<button id="add">Add one</button>
<script>
let store;
try { localStorage.setItem('t','1'); localStorage.removeItem('t'); store = localStorage; }
catch (e) { const m = {}; store = { getItem: k => (k in m ? m[k] : null), setItem: (k, v) => { m[k] = String(v); } }; }
const n = document.getElementById('n');
let total = Number(store.getItem('total')) || 0;
n.textContent = total;
// on click: total++, save it, show it
</script>
document.getElementById(‘add’).addEventListener(‘click’, () => { total++; store.setItem(‘total’, total); n.textContent = total; });
<style>body{font-family:Arial;padding:14px;text-align:center} #n{font-size:56px;font-weight:800;color:#5A28C8} button{padding:10px 18px;background:#5A28C8;color:#fff;border:0;border-radius:8px}</style>
<div id="n">0</div>
<button id="add">Add one</button>
<script>
let store;
try { localStorage.setItem('t','1'); localStorage.removeItem('t'); store = localStorage; }
catch (e) { const m = {}; store = { getItem: k => (k in m ? m[k] : null), setItem: (k, v) => { m[k] = String(v); } }; }
const n = document.getElementById('n');
let total = Number(store.getItem('total')) || 0;
n.textContent = total;
document.getElementById('add').addEventListener('click', function () {
total++;
store.setItem('total', total);
n.textContent = total;
});
</script>
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What type are all localStorage values?
- Numbers
- Objects
- Booleans
- Strings
Everything is stored as text.
How do you store an array in localStorage?
- setItem directly
JSON.stringifythen setItem- Not possible
- Use cookies only
Convert to JSON text first.
What does getItem return for a missing key?
undefined- An empty string
- An error
null
It returns null.
How long does sessionStorage last?
- Until the tab is closed
- Forever
- One day
- One hour
It is cleared when the tab closes.
What should you never keep in localStorage?
- Theme choice
- Font size
- Passwords or secrets
- Last visited page
Anyone with access to the device can read it.
Summary
- localStorage keeps text per site until cleared.
- Use JSON.stringify and JSON.parse for objects and arrays.
- Wrap storage in try/catch helpers with fallbacks.
- Never store secrets.
Questions
Can visitors see or edit my localStorage?
Yes, through developer tools. Never trust it for security.
Why is localStorage empty in my editor preview?
Sandboxed frames block real storage. Use your own page or a stand-in as shown.
How much can I store?
Usually about 5 MB per site. For more, use IndexedDB.
