What is Web Storage?
Web Storage is a browser feature that allows websites to store data locally in the userβs browser.
It is mainly used for saving small amounts of data like preferences, login state, or form inputs.
Think of it as a small notebook inside the browser.
What is localStorage?
localStorage stores data with no expiration time. The data remains even after closing and reopening the browser.
// Save data localStorage.setItem("username", "Rahul"); // Get data let user = localStorage.getItem("username");
What is sessionStorage?
sessionStorage stores data only for the current browser tab session. Once the tab is closed, the data is deleted.
// Save data sessionStorage.setItem("theme", "dark"); // Get data let theme = sessionStorage.getItem("theme");
Key differences
- π’ Persistence β localStorage: permanent, sessionStorage: temporary
- π’ Scope β localStorage: all tabs, sessionStorage: single tab
- π’ Lifetime β localStorage: until manually cleared, sessionStorage: until tab closes
Comparison table
Feature | localStorage | sessionStorage --------------------------------------------------------- Lifetime | Permanent | Until tab closes Scope | All tabs | Single tab Cleared on close | No | Yes
When to use localStorage
- Saving user preferences (theme, language)
- Keeping user logged in (non-sensitive data)
- Storing app settings
When to use sessionStorage
- Temporary form data
- Multi-step form progress
- Data that should not persist after tab closes
Both storage types are synchronous and limited in size (~5β10MB depending on browser).
Summary
localStorage is for long-term browser storage, while sessionStorage is for temporary data within a single tab session.
Both are simple, powerful tools for storing small amounts of data in the browser.