Frontend development · Beginner · 25 min
Remember user settings with localStorage and sessionStorage
By Padding · Updated 18 Nov 2026
Modern browsers · Web Storage API (HTML Living Standard) · checked in Chromium 159 · Node.js 26.13
You will build a small notes page whose theme and text size survive a reload and follow the reader across tabs, with a half-written note kept per tab, storage failures handled without errors and old saved data upgraded safely.
On this page
A settings screen that forgets everything on reload feels broken, and a note that vanishes when a flaky connection reloads the page is worse. The browser has two small key-value stores built for this: localStorage, which keeps data for a site until someone clears it, and sessionStorage, which keeps data for one tab until that tab closes. Both are a few lines to use and easy to use badly.
In this tutorial you build Field notes, a one-page notes screen with two settings (theme and text size) and a text box for a note. By the end:
- the settings survive a reload and a browser restart, and a change in one tab shows up in every other open tab
- the half-written note survives a reload of its own tab but does not leak into other tabs
- corrupted or old saved data, a full store and a browser that blocks storage all leave the page working
- a Playwright test proves all of it in a real browser
The theme CSS here is deliberately short. For a full light and dark palette, contrast checks and the inline script that stops a flash of the wrong theme, follow add dark mode with CSS variables; this tutorial is about the storage side.
Step 1 · Set up the page and a local server
Storage belongs to an origin, which is the scheme, host and port together, so http://127.0.0.1:8080 and http://localhost:8080 have separate stores. Pages opened straight from disk with file:// behave differently from browser to browser, so serve the page over HTTP from the start.
Make a demo folder with the page, a short stylesheet and an empty script:
mkdir -p ~/fieldnotes-demo
cd ~/fieldnotes-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Field notes</title>
<link rel="stylesheet" href="style.css">
<script type="module" src="app.js"></script>
</head>
<body>
<main>
<h1>Field notes</h1>
<form id="settings">
<fieldset>
<legend>Theme</legend>
<label><input type="radio" name="theme" value="system" checked> Match my device</label>
<label><input type="radio" name="theme" value="light"> Light</label>
<label><input type="radio" name="theme" value="dark"> Dark</label>
</fieldset>
<label for="text-size">Text size</label>
<select id="text-size" name="textSize">
<option value="normal">Normal</option>
<option value="large">Large</option>
</select>
</form>
<label for="note">Note</label>
<textarea id="note" rows="6"></textarea>
<p id="status" role="status"></p>
</main>
</body>
</html>
HTML
cat > style.css <<'CSS'
:root {
color-scheme: light dark;
--bg: light-dark(#ffffff, #121417);
--text: light-dark(#1b1f24, #e8eaed);
}
:root[data-theme="light"] { color-scheme: light; }
:root[data-theme="dark"] { color-scheme: dark; }
:root[data-text-size="large"] { font-size: 125%; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 1rem/1.5 system-ui, sans-serif;
}
main { max-width: 32rem; margin: 0 auto; padding: 1rem; }
fieldset { margin: 0 0 1rem; }
label { display: block; margin: 0.25rem 0; }
select, textarea { box-sizing: border-box; width: 100%; font: inherit; margin-bottom: 1rem; }
CSS
touch app.jsdata-theme on the <html> element forces light or dark, and with no attribute the page follows the device setting. data-text-size="large" scales every rem by 125 per cent. The script will only ever set those two attributes.
Now a server. Node.js has no built-in static file server, so write a small one that serves only the page's own .html, .css and .js files:
cd ~/fieldnotes-demo
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join } from 'node:path';
const types = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
};
export function start(port = 8080) {
const server = createServer(async (req, res) => {
const path = new URL(req.url, 'http://localhost').pathname;
const file = path === '/' ? 'index.html' : path.slice(1);
if (!types[extname(file)] || file.includes('/')) {
res.writeHead(404).end('Not found');
return;
}
try {
const body = await readFile(join(import.meta.dirname, file));
res.writeHead(200, { 'content-type': types[extname(file)] }).end(body);
} catch {
res.writeHead(404).end('Not found');
}
});
return new Promise((resolve) => server.listen(port, '127.0.0.1', () => resolve(server)));
}
if (import.meta.main) {
await start();
console.log('Open http://127.0.0.1:8080');
}
JS
node --check server.mjsThe server exports start() so the browser test at the end can start the same server on a free port. import.meta.main is true only when you run the file directly. Start it in its own terminal window and leave it running:
cd ~/fieldnotes-demo
node server.mjsCheck it worked
The terminal prints Open http://127.0.0.1:8080. Open that address. You see the Field notes heading, a Theme box with three choices, a Text size menu and an empty Note box. Choosing Dark does nothing yet, and the choice is lost when you reload.
Step 2 · Save the theme with setItem and getItem
The whole Web Storage API is five methods on localStorage and sessionStorage: setItem(key, value), getItem(key), removeItem(key), clear() and key(index), plus a length. Keys and values are always strings, and getItem returns null for a key that was never set.
Write a first version of the script that saves the theme as a plain string:
cd ~/fieldnotes-demo
cat > app.js <<'JS'
const form = document.querySelector('#settings');
const root = document.documentElement;
function applyTheme(theme) {
if (theme === 'light' || theme === 'dark') root.dataset.theme = theme;
else delete root.dataset.theme;
}
const savedTheme = localStorage.getItem('theme');
console.log('Saved theme:', savedTheme);
if (savedTheme) {
form.elements.theme.value = savedTheme;
applyTheme(savedTheme);
}
form.addEventListener('change', () => {
const theme = form.elements.theme.value;
localStorage.setItem('theme', theme);
applyTheme(theme);
});
JSform.elements.theme is the group of three radios, and setting its value ticks the radio with that value. Reading the saved value into the form, not only into the page, matters: otherwise the page is dark but the form still says Match my device.
What never goes in localStorage
Anything in localStorage can be read by every script running on your origin, stays on the disk after the person signs out, and can be edited by the person in DevTools. So keep it for preferences and harmless convenience data. Never store:
- Access tokens, session IDs or API keys. A single cross-site scripting bug lets an attacker's script read them. Keep sign-in in an
HttpOnly,Securecookie that scripts cannot read at all. - Personal data such as names, phone numbers, health or payment details. On a phone shared by a family, or a computer in a library, the next person can read it.
- Anything the server must trust, such as a price, a role or an "is admin" flag. Treat everything read back as user input.
Check it worked
Reload the page and open the browser console (in Chrome or Edge, press F12 and pick Console). It shows Saved theme: null. Choose Dark: the page turns dark. Reload: the console shows Saved theme: dark, the page loads dark and Dark is ticked. In Chrome or Edge, the Application panel under Storage, Local storage, http://127.0.0.1:8080 lists the key theme with the value dark.
Step 3 · Store all settings as one JSON object
With two settings you could use two keys, but one object per feature is easier to version and reset. Because values must be strings, convert with JSON.stringify on the way in and JSON.parse on the way out. Try what happens without that in the console:
localStorage.setItem('demo', { textSize: 'large' });
localStorage.getItem('demo'); // "[object Object]"
localStorage.removeItem('demo');The object was turned into the useless string "[object Object]". Reading back safely needs three guards, because the stored text may be missing, may not be valid JSON (someone edited it, or an old release wrote something else), or may parse into the wrong shape. Put the storage calls in one small module that never throws:
cd ~/fieldnotes-demo
cat > storage.js <<'JS'
// Safe wrappers around localStorage ('local') and sessionStorage ('session').
// Every one of these can fail in a browser, so none of these functions throw.
function area(kind) {
try {
return kind === 'session' ? window.sessionStorage : window.localStorage;
} catch {
return null; // the browser is blocking storage for this site
}
}
export function readText(kind, key) {
try {
return area(kind)?.getItem(key) ?? null;
} catch {
return null;
}
}
export function writeText(kind, key, value) {
try {
const store = area(kind);
if (!store) return false;
store.setItem(key, value);
return true;
} catch {
return false; // full (QuotaExceededError) or blocked
}
}
export function removeKey(kind, key) {
try {
area(kind)?.removeItem(key);
} catch {
// nothing to do
}
}
export function readJSON(kind, key) {
const text = readText(kind, key);
if (text === null) return null;
try {
return JSON.parse(text);
} catch {
return null; // not valid JSON
}
}
export function writeJSON(kind, key, value) {
return writeText(kind, key, JSON.stringify(value));
}
JSThen a settings module that knows the allowed values and falls back to a default for anything else. The key carries a prefix, because every script on the origin shares one localStorage, and a version, which a later step relies on:
cd ~/fieldnotes-demo
cat > settings.js <<'JS'
import { readJSON, writeJSON } from './storage.js';
export const SETTINGS_KEY = 'fieldnotes.settings.v1';
const DEFAULTS = { theme: 'system', textSize: 'normal' };
const ALLOWED = {
theme: ['system', 'light', 'dark'],
textSize: ['normal', 'large'],
};
// Keep only known settings with allowed values; use the default for the rest.
export function cleanSettings(raw) {
const clean = { ...DEFAULTS };
if (raw && typeof raw === 'object') {
for (const name of Object.keys(DEFAULTS)) {
if (ALLOWED[name].includes(raw[name])) clean[name] = raw[name];
}
}
return clean;
}
export function loadSettings() {
return cleanSettings(readJSON('local', SETTINGS_KEY));
}
export function saveSettings(settings) {
return writeJSON('local', SETTINGS_KEY, cleanSettings(settings));
}
export function applySettings(settings, form) {
const root = document.documentElement;
if (settings.theme === 'system') delete root.dataset.theme;
else root.dataset.theme = settings.theme;
root.dataset.textSize = settings.textSize;
form.elements.theme.value = settings.theme;
form.elements.textSize.value = settings.textSize;
}
JS
touch migrate.jsmigrate.js stays empty for now. It is imported first, so that upgrades of old saved data always run before anything reads settings. Replace app.js with a version that uses the two modules:
cd ~/fieldnotes-demo
cat > app.js <<'JS'
import './migrate.js';
import { readText, writeText, removeKey } from './storage.js';
import { SETTINGS_KEY, loadSettings, saveSettings, applySettings } from './settings.js';
const form = document.querySelector('#settings');
const statusLine = document.querySelector('#status');
const say = (message) => { statusLine.textContent = message; };
applySettings(loadSettings(), form);
form.addEventListener('change', () => {
const settings = {
theme: form.elements.theme.value,
textSize: form.elements.textSize.value,
};
applySettings(settings, form);
if (!saveSettings(settings)) {
say('Settings changed for this visit only. This browser is not letting the page save them.');
}
});
JSSome imports are not used yet; the next steps add code below this that uses them. Changing a setting still applies it straight away when saving fails, so the person is never stuck.
Check it worked
Reload. The page is back to Match my device, because the settings now live under a new key; the old theme key is still there and comes back in the versioning step. Choose Dark and Large: the page turns dark and the text grows. In the console, localStorage.getItem('fieldnotes.settings.v1') returns '{"theme":"dark","textSize":"large"}'. Now break it on purpose:
localStorage.setItem('fieldnotes.settings.v1', '{"theme": "purple", oops');Reload. The page loads with the defaults and the console shows no error. Choose Dark and Large again to put valid data back.
Step 4 · Keep a half-written note per tab with sessionStorage
sessionStorage has the same methods, but its data belongs to one tab. It survives reloads and going back and forward, and it is cleared when the tab closes. A new tab starts with an empty session (duplicating a tab copies it, in most browsers). That fits a draft: it survives a reload or a dropped connection, two tabs can hold two different drafts, and closing the tab leaves nothing behind on a shared device.
Add the draft code to the end of app.js:
cd ~/fieldnotes-demo
cat >> app.js <<'JS'
// The half-written note lives in this tab only.
const DRAFT_KEY = 'fieldnotes.draft';
const note = document.querySelector('#note');
note.value = readText('session', DRAFT_KEY) ?? '';
note.addEventListener('input', () => {
if (!writeText('session', DRAFT_KEY, note.value)) {
say('This note will be lost if the tab reloads. The browser is not letting the page save it.');
}
});
JSSaving on every keystroke is fine for a short note, because each write is tiny. Web Storage calls are synchronous and block the page while they run, so for long documents save after a short pause in typing instead.
On a low-end Android phone, Chrome may unload a background tab to free memory and reload it when you return. A draft in sessionStorage is usually still there when that happens, which spares the reader retyping on a small keyboard. Text in any script, such as Yoruba with its tone marks or Amharic, is stored exactly as typed.
Check it worked
Type Buy airtime before Friday in the Note box and reload: the text is still there. Open http://127.0.0.1:8080 in a new tab: its Note box is empty, but it uses your saved theme and text size. Close the first tab and open the address again: the note is gone.
Step 5 · Sync settings across tabs with the storage event
Open two tabs on the page and change the theme in one. The other keeps the old theme until it reloads. When localStorage changes, the browser fires a storage event in every other tab on the same origin, though not in the tab that made the change. Listen for it and re-apply the settings:
cd ~/fieldnotes-demo
cat >> app.js <<'JS'
// Another tab changed localStorage. key is null when it called clear().
window.addEventListener('storage', (event) => {
if (event.key === SETTINGS_KEY || event.key === null) {
applySettings(loadSettings(), form);
}
});
JSThe handler reads the value again through loadSettings() rather than trusting event.newValue, so the same cleaning and defaults apply. Changes to sessionStorage do not reach other tabs, which is what you want for the draft.
Check it worked
Open the page in two tabs side by side, or switch between them. In the first tab choose Light; the second tab turns light without a reload and its Light radio is ticked. Change Text size in the second tab: the first follows.
Step 6 · Handle full or blocked storage
Three things can make storage fail:
- The store is full. Browsers allow about 5 MiB of
localStorageper origin, andsetItemthrows aQuotaExceededErrorpast that. - Storage is blocked. If someone blocks site data in the browser settings, even reading
window.localStoragecan throw aSecurityError. - Private windows. Most current browsers keep storage working in a private window and wipe it when the window closes, so nothing lasts. Older browsers threw on every write.
storage.js already catches all of these, so the page keeps working. What is missing is telling the person once, when the page loads, that their choices will not last. Add a small write test to the end of app.js:
cd ~/fieldnotes-demo
cat >> app.js <<'JS'
// Say once, at start-up, if nothing will be remembered.
if (writeText('local', 'fieldnotes.probe', '1')) {
removeKey('local', 'fieldnotes.probe');
} else {
say('This browser is not saving settings for this site, so they will reset next time.');
}
JSThe message goes in the role="status" paragraph, so screen readers announce it without moving focus.
Check it worked
See a real quota error first. In the console run:
try { localStorage.setItem('filler', 'x'.repeat(20_000_000)); } catch (e) { console.log(e.name); }Chrome prints QuotaExceededError; other browsers may use a different name. Nothing is stored, because the write failed as a whole. Now make every write fail for this page, the way a blocked or full store would:
Storage.prototype.setItem = () => { throw new DOMException('Full', 'QuotaExceededError'); };Change the Text size. The text changes size anyway and the status line reads Settings changed for this visit only..., with no red error in the console. Reload, which restores the real setItem: the page comes back with the size saved before the override.
Step 7 · Version your keys so old data cannot break a release
Your first version stored the theme as a bare string under theme. Anyone who used that release still has it, and the current code ignores it, so to them it looks as if their setting was lost. Worse, code that ran JSON.parse on "dark" would throw.
The .v1 in fieldnotes.settings.v1 is the fix for next time: when the saved shape changes, the new release uses a new key, so it never reads a shape it does not understand, and an older tab still open reads its own key. For data already out there, add a migration that runs once, before anything reads settings. Fill in migrate.js:
cd ~/fieldnotes-demo
cat > migrate.js <<'JS'
// Upgrade older saved data before anything reads settings.
// Each block moves one old shape to the current key, then removes the old key.
import { readText, readJSON, writeJSON, removeKey } from './storage.js';
// Release 1 stored only the theme, as a bare string under "theme".
const oldTheme = readText('local', 'theme');
if (oldTheme !== null) {
const alreadyMoved = readJSON('local', 'fieldnotes.settings.v1') !== null;
const moved = alreadyMoved
|| writeJSON('local', 'fieldnotes.settings.v1', { theme: oldTheme, textSize: 'normal' });
if (moved) removeKey('local', 'theme');
}
JSTwo details keep this safe. The old key is removed only after the new one is written, so a full store never loses the setting. And the old value is not trusted: cleanSettings in settings.js replaces anything that is not system, light or dark with the default.
When the shape changes again, say a release replaces textSize with a numeric textScale, add another block in the same pattern (read v1, write v2, remove v1) and point SETTINGS_KEY at fieldnotes.settings.v2:
const v1 = readJSON('local', 'fieldnotes.settings.v1');
if (v1 && readJSON('local', 'fieldnotes.settings.v2') === null) {
const textScale = v1.textSize === 'large' ? 125 : 100;
if (writeJSON('local', 'fieldnotes.settings.v2', { theme: v1.theme, textScale })) {
removeKey('local', 'fieldnotes.settings.v1');
}
}That block is only an example; leave it out of your file.
Check it worked
Pretend to be a visitor from release 1. In the console run:
localStorage.clear();
localStorage.setItem('theme', 'dark');
location.reload();The page loads dark with Dark ticked. localStorage.getItem('theme') now returns null, and localStorage.getItem('fieldnotes.settings.v1') returns '{"theme":"dark","textSize":"normal"}'.
Step 8 · Test it in a real browser
Clicking through two tabs by hand proves it once. A test proves it after every change. Install Playwright, which drives a real browser from a script, into the demo folder. --with-deps also installs the system libraries Chromium needs on Linux and can ask for your password:
cd ~/fieldnotes-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromiumThe test starts the server on a free port, then checks each promise from the start of this tutorial: settings survive a reload, the draft stays in its own tab, tabs sync, old and broken data are handled, and failed writes give a message instead of an error.
cd ~/fieldnotes-demo
cat > test-settings.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { start } from './server.mjs';
const server = await start(0);
const url = `http://127.0.0.1:${server.address().port}/`;
const browser = await chromium.launch();
const theme = (page) => page.evaluate(() => document.documentElement.dataset.theme ?? 'system');
const stored = (page, key) => page.evaluate((k) => localStorage.getItem(k), key);
try {
const context = await browser.newContext();
const tabA = await context.newPage();
const errors = [];
tabA.on('pageerror', (e) => errors.push(e.message));
await tabA.goto(url);
// Settings survive a reload, in the page and in the form.
await tabA.getByLabel('Dark', { exact: true }).check();
await tabA.getByLabel('Text size').selectOption('large');
assert.deepEqual(JSON.parse(await stored(tabA, 'fieldnotes.settings.v1')), { theme: 'dark', textSize: 'large' });
await tabA.reload();
assert.equal(await theme(tabA), 'dark');
assert.ok(await tabA.getByLabel('Dark', { exact: true }).isChecked());
assert.equal(await tabA.getByLabel('Text size').inputValue(), 'large');
assert.equal(await tabA.evaluate(() => getComputedStyle(document.body).backgroundColor), 'rgb(18, 20, 23)');
assert.equal(await tabA.evaluate(() => getComputedStyle(document.documentElement).fontSize), '20px');
// The draft survives a reload of its own tab, and a new tab starts empty.
const words = 'Ẹ kú àárọ̀. Buy airtime before Friday.';
await tabA.getByLabel('Note', { exact: true }).fill(words);
await tabA.reload();
assert.equal(await tabA.getByLabel('Note', { exact: true }).inputValue(), words);
const tabB = await context.newPage();
await tabB.goto(url);
assert.equal(await tabB.getByLabel('Note', { exact: true }).inputValue(), '');
assert.equal(await theme(tabB), 'dark', 'a new tab uses the saved settings');
// A change in one tab reaches the other without a reload.
await tabB.getByLabel('Light', { exact: true }).check();
await tabA.waitForFunction(() => document.documentElement.dataset.theme === 'light');
assert.ok(await tabA.getByLabel('Light', { exact: true }).isChecked());
// A release 1 visitor is migrated to the versioned key.
await tabA.evaluate(() => { localStorage.clear(); localStorage.setItem('theme', 'dark'); });
await tabA.reload();
assert.equal(await theme(tabA), 'dark');
assert.equal(await stored(tabA, 'theme'), null);
assert.deepEqual(JSON.parse(await stored(tabA, 'fieldnotes.settings.v1')), { theme: 'dark', textSize: 'normal' });
// Broken JSON falls back to the defaults.
await tabA.evaluate(() => localStorage.setItem('fieldnotes.settings.v1', '{"theme": "purple", oops'));
await tabA.reload();
assert.equal(await theme(tabA), 'system');
assert.deepEqual(errors, [], 'no uncaught errors');
// When every write fails, the page still works and says so.
const failing = await browser.newContext();
await failing.addInitScript(() => {
Storage.prototype.setItem = () => { throw new DOMException('Full', 'QuotaExceededError'); };
});
const tabC = await failing.newPage();
const errorsC = [];
tabC.on('pageerror', (e) => errorsC.push(e.message));
await tabC.goto(url);
await tabC.getByText('not saving settings for this site').waitFor();
await tabC.getByLabel('Dark', { exact: true }).check();
assert.equal(await theme(tabC), 'dark');
await tabC.getByText('Settings changed for this visit only').waitFor();
assert.deepEqual(errorsC, [], 'no uncaught errors when storage fails');
} finally {
await browser.close();
server.close();
}
console.log('PASS: settings remembered, synced and safe');
JS
node test-settings.mjsEach tab in one Playwright context shares localStorage, like tabs in one browser window, while a new context is like a separate browser profile with its own stores. The init script in the last block replaces setItem before the page's own code runs, which is how the test makes storage fail on demand.
Check it worked
The last line of output is PASS: settings remembered, synced and safe. To see it fail for the right reason, delete the storage listener block from app.js and run node test-settings.mjs again: it stops after about 30 seconds with a timeout on waitForFunction and no PASS line. Put the block back and the test passes again.
Step 9 · Clean up
The settings live in your browser, not in the demo folder. On the Field notes tab, run localStorage.clear() in the console, or in Chrome use the Application panel and Clear site data. Then stop the server with Ctrl+C in its terminal and remove the folder, which also removes the local Playwright install:
cd ~
rm -rf ~/fieldnotes-demoThe browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes it if you no longer need it.
Check it worked
ls ~/fieldnotes-demo reports that there is no such file or directory, and http://127.0.0.1:8080 no longer loads.
Next steps
- Give the theme setting a full palette and stop the flash of the wrong theme on load in add dark mode with CSS variables.
- Keep settings and other app data in one place that saves itself in manage app state in plain JavaScript with a store.
- Make status messages like the ones here announce reliably in announce errors and notices with a live region.
- See how the page behaves on a slow, metered connection in test and speed up a page on a slow phone connection.
Related tutorials
- How to Add Dark Mode to a Website with CSS VariablesYou will define your colours once as CSS custom properties, switch them with light-dark() and the user's system setting, add a toggle button that remembers the choice without a flash on reload, and check the text contrast of both themes with a short script.
- Manage app state in plain JavaScript with a store and eventsYou will build a shopping list app with no framework, where one state object, a small store built on EventTarget and a render function keep the screen and the data in step, with derived counts and a list that survives a reload.
- Announce errors and notices with a live regionYou will build two Larkfield Clinic banners, a polite "10:30 was just taken" notice and an urgent "could not book" error, that screen readers announce once each, plus a Playwright script that checks them in the accessibility tree.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials