Stop 08 · The DOM & Browser APIsTopics · 6/6

LocalStorage

Part of the Web Development Roadmap

In short

Want your app to remember dark mode or a half-written note even after the tab closes? localStorage gives you a small, simple storage box right in the browser.

localStorage saves small amounts of string data in the browser so it survives a page refresh, which is handy for settings or a simple to-do list.

The jaadu puts a bag into its college locker and turns the key.

Think of it like this

Your locker at college

You keep stuff there and it stays for days, until you clear it. But it's only at your college: another college (website) has its own lockers and can't open yours.

Watch it happen

Saving dark mode

Your code
localStorage

setItem('theme', 'dark')

1/5You save the user's choice under a key.

The big ideas

What you need to know

Strings only

localStorage stores key-value pairs as strings. Use JSON.stringify to save objects and JSON.parse to read them.

It doesn't expire

Data stays until your code or the user clears it, even after the browser restarts.

One box per site

Each origin (protocol + domain + port) gets its own storage, usually around 5 MB.

Not for secrets

Any script on the page can read it, so never keep passwords or login tokens there.

See it in code

Walk through the code

js
1const settings = { theme: "dark", fontSize: 16 };2 3// Save (objects must become strings)4localStorage.setItem("settings", JSON.stringify(settings));5 6// Read it back, with a safe default7const saved = JSON.parse(localStorage.getItem("settings") ?? "{}");8 9// Remove one key, or everything10localStorage.removeItem("settings");11localStorage.clear();

1/3Objects must become strings first, so JSON.stringify before saving.

getItem returns null when nothing is saved, so the ?? "{}" fallback stops JSON.parse from failing.

Save yourself the pain

Common mistakes

Oops

Saving an object directly, which stores '[object Object]'.

Do this instead

Always JSON.stringify before saving and JSON.parse when reading.

Oops

Keeping a login token in localStorage.

Do this instead

Keep auth tokens in HttpOnly cookies. Use localStorage for harmless things like theme or filters.

Oops

Reading localStorage while a Next.js page renders on the server.

Do this instead

Read it inside useEffect or other browser-only code, because it doesn't exist on the server.

Your mission

A theme switch that remembers

~20 min

Quick check

You run localStorage.setItem('user', { name: 'Riya' }). What gets saved?

Go deeper

  1. 1Save a theme choice in localStorage and apply it when the page loads.
  2. 2Store an array by converting it with JSON.stringify and reading it with JSON.parse.
  3. 3Never store passwords or tokens you can't afford to leak in localStorage.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge