HTML Web Storage


HTML Web Storage gives your website a simple way to store data directly inside the user’s browser. It works without a database, cookies or server code. The browser keeps the data safe and separate for each website, and you can read or update it anytime with JavaScript. Web Storage is mainly used for saving user preferences, login states, theme settings, form data, cart items and any information that should stay even after a page refresh. In this tutorial, you’ll learn what Web Storage is, how it works, the difference between localStorage and sessionStorage, and how you can store, update, remove and clear data easily.

What is Web Storage?

Web Storage is a browser feature that gives websites a private storage space. This space is much larger than cookies and is not sent automatically with every request, which makes it faster and more secure. Web Storage has two parts:

  • localStorage – Data stays even after closing the browser.

  • sessionStorage – Data stays only for the current browser tab.

Both work with simple key-value pairs and use JavaScript methods.

Why Web Storage is useful

Web Storage helps you keep information on the client side. Here are a few examples:

  • Save dark/light theme choice

  • Keep cart items in an ecommerce site

  • Store the last visited page

  • Auto-fill user input

  • Track if popups should still be shown

  • Save game scores or progress

  • Manage simple app settings

Because the data stays in the browser, the user gets a smoother experience without repeated server requests.

Difference between localStorage and sessionStorage

Although both store key-value data, they behave differently.

Feature localStorage sessionStorage
Lifespan Until manually deleted Until the tab/window is closed
Scope Shared across all tabs of the same domain Unique to each tab
Storage Size 5MB to 10MB (varies by browser) 5MB (usually)
Use Case Long-term settings Temporary session data

localStorage is great for things that must stay.
sessionStorage is perfect for short tasks like forms or quizzes.

How to check if the browser supports Web Storage

Although modern browsers support it, it’s good practice to check:

if (typeof(Storage) !== "undefined") {
    console.log("Web Storage supported");
} else {
    console.log("Web Storage not supported");
}

This prevents errors in old or restricted browsers.

How to store data in localStorage

Storing data inside localStorage is simple. You use localStorage.setItem() with a key and a value.

Example:

localStorage.setItem("username", "Anita");

This saves the username permanently in the browser.

You can confirm it using:

console.log(localStorage.getItem("username"));

How to update stored data

If you set the same key again, the value will automatically update.

localStorage.setItem("username", "Meera");

This replaces “Anita” with “Meera”.

How to remove a specific item

Use removeItem() when you want to delete one key.

localStorage.removeItem("username");

This deletes only the username.

How to clear all data

Use localStorage.clear() to wipe everything stored by your site.

localStorage.clear();

This is helpful when you want a reset button or logout action.

Working with numbers, arrays and objects

localStorage stores only strings. So if you want to store arrays or objects, you need JSON.

Storing a number

localStorage.setItem("score", 25);

Storing an array

let colors = ["red", "blue", "green"];
localStorage.setItem("colors", JSON.stringify(colors));

To read it:

let storedColors = JSON.parse(localStorage.getItem("colors"));
console.log(storedColors);

Storing an object

let user = { name: "Kavita", age: 22 };
localStorage.setItem("user", JSON.stringify(user));

And retrieve it:

let storedUser = JSON.parse(localStorage.getItem("user"));

Using sessionStorage

sessionStorage works almost the same, but the data disappears when the tab closes.

Storing:

sessionStorage.setItem("temp", "Session active");

Reading:

console.log(sessionStorage.getItem("temp"));

Removing:

sessionStorage.removeItem("temp");

Clearing:

sessionStorage.clear();

Use sessionStorage when you want temporary behavior like:

  • Form steps

  • Short tests

  • Checkout progress

  • Temporary filters

Example: Remembering dark mode with localStorage

A very common use is saving theme selection.

HTML

<button id="themeBtn">Toggle Theme</button>

JavaScript

const btn = document.getElementById("themeBtn");

if (localStorage.getItem("theme") === "dark") {
    document.body.classList.add("dark");
}

btn.addEventListener("click", function() {
    document.body.classList.toggle("dark");

    if (document.body.classList.contains("dark")) {
        localStorage.setItem("theme", "dark");
    } else {
        localStorage.setItem("theme", "light");
    }
});

Here, the body remains in dark mode even after reloading or closing the browser.

Example: Simple cart using localStorage

let cart = [];

if (localStorage.getItem("cart")) {
    cart = JSON.parse(localStorage.getItem("cart"));
}

function addToCart(item) {
    cart.push(item);
    localStorage.setItem("cart", JSON.stringify(cart));
}

With this, the cart stays saved even after refreshing.

Example: Saving form data temporarily

const input = document.getElementById("email");

input.addEventListener("input", function() {
    sessionStorage.setItem("email", input.value);
});

input.value = sessionStorage.getItem("email") || "";

This helps users continue where they left off.

When Web Storage should not be used

Web Storage is great, but there are situations where you should avoid it:

  • Sensitive information (passwords, tokens)

  • Large data files

  • Very complex structured data

  • Information shared across multiple users

  • Situations requiring guaranteed reliability

For these cases, use a database or server-side storage.

Summary of HTML Web Storage

HTML Web Storage gives you a simple way to store data directly inside the browser. It includes localStorage for long-term data and sessionStorage for temporary data. You can save, read, update, delete and clear data using simple JavaScript methods. You can also store arrays and objects using JSON. Web Storage is perfect for themes, forms, carts, settings and small app data. It improves speed and user experience because everything happens on the client side. With the examples above, you can start using Web Storage confidently in your HTML projects.


Practice Questions

Q1. Store a user's name in localStorage and display it on page load.

Q2. Save a user's theme preference (light/dark) in sessionStorage.

Q3. Remove a specific item from localStorage on button click.

Q4. Clear all sessionStorage when user logs out.

Q5. Use localStorage to keep track of the number of visits to a page.

Q6. Store form data temporarily using sessionStorage.

Q7. Update an existing value in localStorage.

Q8. Check if a key exists in localStorage before using it.

Q9. Use localStorage to save a user's language preference.

Q10. Implement a toggle that switches theme and stores the current selection using Web Storage.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top