AniUI Academy

Browser Storage and Persisting Data

Save user data in the browser so game scores, dark mode settings, and app states survive page reloads using localStorage and sessionStorage.

10 min read

Imagine playing a video game on the web, reaching level 10, accidentally refreshing the page, and losing all your progress. That would be frustrating, and by default it is exactly what happens.

By default, JavaScript variables live in the browser's temporary memory (RAM). The moment a page refreshes or navigates away, every variable is wiped clean.

To solve this, web browsers provide Web Storage APIs — specifically localStorage and sessionStorage. They act like a small notebook built into the user's browser, letting your site remember settings, high scores, themes and shopping cart items between visits.

localStorage

Saves data permanently on the user's device. Survives tab closes, browser restarts, and system reboots.

sessionStorage

Saves data temporarily. Cleared automatically the instant the user closes the browser tab.

Both give you around 5MB of space per domain, which is plenty of room for text, user preferences and app state.

The storage methods

Both localStorage and sessionStorage provide 4 primary methods:

1. Saving data: setItem(key, value)

// Store simple text strings
localStorage.setItem("theme", "dark");
localStorage.setItem("username", "Alex");

2. Reading data: getItem(key)

const savedTheme = localStorage.getItem("theme");
console.log(savedTheme); // "dark"
 
// If a key does not exist, getItem returns null
const missing = localStorage.getItem("nonExistentKey");
console.log(missing); // null

3. Removing a single item: removeItem(key)

localStorage.removeItem("username");

4. Clearing everything: clear()

localStorage.clear(); // Removes ALL key-value pairs stored for your site

Storing objects and arrays with JSON

Here is the most important rule of Web Storage: localStorage only stores text strings.

  1. Step 1

    1. Live JS Object

    const user = { name: 'Sam', score: 450 }

  2. Step 2

    2. JSON.stringify(user)

    Converts object to '{"name":"Sam","score":450}'

  3. Step 3

    3. setItem('user', string)

    Safely stores text string in browser storage

  4. Step 4

    4. JSON.parse(storedString)

    Parses retrieved string back into live JS object

How to safely store complex objects and arrays in Web Storage

If you try to save a JavaScript object or array directly without JSON conversion:

const user = { name: "Sam", score: 450 };
localStorage.setItem("currentUser", user);
 
// Reading it back:
console.log(localStorage.getItem("currentUser")); // "[object Object]" -- the data is gone

To store objects and arrays correctly, turn them into JSON strings using JSON.stringify() before saving, and parse them back with JSON.parse() when reading:

const user = { name: "Sam", score: 450 };
 
// 1. Save object as JSON string
localStorage.setItem("currentUser", JSON.stringify(user));
 
// 2. Retrieve JSON string and parse back to object
const rawData = localStorage.getItem("currentUser");
if (rawData) {
  const loadedUser = JSON.parse(rawData);
  console.log(loadedUser.name); // "Sam"
  console.log(loadedUser.score); // 450
}

Try it yourself

Save a high score and read it back. Change the score, run it again, and notice that the second run reads what the first one wrote.

Try it yourself
Loading playground...

When not to use localStorage

Useful as it is, localStorage comes with two rules worth treating as absolute:

  1. Never store passwords, API secret keys, or card numbers in localStorage. Any script or browser extension running on the page can read localStorage. Store sensitive auth tokens in HttpOnly cookies instead.
  2. Do not use it as a full database for huge datasets. For megabytes of complex offline relational data, use IndexedDB.

What to remember

localStorage saves data in the browser until something deletes it, while sessionStorage clears when the tab closes. Store items using setItem(key, value) and read them with getItem(key). Use JSON.stringify() and JSON.parse() whenever you save objects or arrays, because only strings survive the trip.

Check yourself

4 questions · pass 3/4 to unlock Asynchronous JavaScript

up to 50
  1. 1.What is the key difference between localStorage and sessionStorage?

  2. 2.What happens if you pass an object directly to localStorage.setItem('user', { name: 'Alex' })?

  3. 3.Which method completely clears all stored items for the current domain in localStorage?

  4. 4.Where is localStorage data stored?

4 left to answer