HTML - HTML Web Storage (LocalStorage and SessionStorage)

HTML Web Storage is a feature that allows websites to store data directly inside the user’s browser. It is introduced in HTML5 as an improvement over cookies. Web storage helps developers save information such as user preferences, login data, themes, or temporary application data without sending it to the server every time.

Web storage provides two main storage objects:

1. LocalStorage

LocalStorage stores data permanently in the browser. The stored data remains available even after the browser is closed and reopened. The data stays until it is manually deleted by the user or removed using code.

Features of LocalStorage:

  • Stores data as key and value pairs.

  • Data does not expire automatically.

  • Accessible only by the same website that stored it.

  • Storage size is larger compared to cookies (usually around 5–10 MB).

Example:

<script>
localStorage.setItem("username", "Teena");

let name = localStorage.getItem("username");
console.log(name);

localStorage.removeItem("username");
</script>

In this example:

  • setItem() saves data.

  • getItem() retrieves stored data.

  • removeItem() deletes specific data.

2. SessionStorage

SessionStorage stores data only for a single browser session. When the browser tab is closed, all stored data is automatically deleted.

Features of SessionStorage:

  • Data exists only while the tab is open.

  • Useful for temporary data such as form progress or session details.

  • Data is not shared between tabs.

Example:

<script>
sessionStorage.setItem("course", "HTML");

let course = sessionStorage.getItem("course");
console.log(course);

sessionStorage.clear();
</script>

Difference Between LocalStorage and SessionStorage

LocalStorage keeps data permanently until removed, while SessionStorage removes data automatically when the browser tab closes. LocalStorage is shared across tabs of the same website, whereas SessionStorage is limited to a single tab.

Advantages of Web Storage

  • Faster than cookies because data is stored locally.

  • Does not send data to the server with every request.

  • Can store larger amounts of data.

  • Easy to use with JavaScript.

Practical Uses

  • Saving user theme preferences.

  • Storing shopping cart data.

  • Remembering form inputs.

  • Maintaining login state on the client side.

HTML Web Storage is widely used in modern web applications to improve performance and provide a better user experience by storing information directly in the browser.