localStorage
and sessionStorage
are both web storage options provided by modern web browsers to store data on the client side (in the user’s browser) without relying on cookies. They are used to store data temporarily or persistently, depending on the use case. However, there are some differences between the two:
- Data Persistence:
localStorage
: Data stored inlocalStorage
persists even after the browser is closed and reopened. It remains available until explicitly cleared by the user or the website that stored it.sessionStorage
: Data stored insessionStorage
is available only for the duration of the page session. If the user closes the browser or tab, the stored data is cleared and not available when the user returns to the page.
- Scope:
- Both
localStorage
andsessionStorage
are domain-specific. Data stored in one domain’slocalStorage
orsessionStorage
is not accessible by other domains.
- Capacity:
localStorage
: Typically has a larger storage capacity compared tosessionStorage
. It’s generally around 5-10 MB per domain, but the exact capacity can vary based on the browser.sessionStorage
: Has a smaller storage capacity compared tolocalStorage
. It’s also usually around 5-10 MB per domain but can vary.
- Usage:
localStorage
: Best suited for long-term storage of data that needs to persist across sessions, such as user preferences or settings.sessionStorage
: Designed for short-term storage of data that is only needed during a single page session, such as maintaining state between different parts of a web application.
- Data Sharing:
- Both
localStorage
andsessionStorage
are only accessible by scripts on the same domain that originally stored the data. - If you want to share data between different tabs or windows of the same browser originating from the same domain, you can use either
localStorage
orsessionStorage
.
- Data Accessibility:
- Data stored in both
localStorage
andsessionStorage
can be accessed using JavaScript on the client side.
Here’s a simple example of how to use localStorage
and sessionStorage
in JavaScript:
// Storing data
localStorage.setItem('key', 'value'); // Persisted across sessions
sessionStorage.setItem('key', 'value'); // Cleared after the session ends
// Retrieving data
const valueFromLocalStorage = localStorage.getItem('key');
const valueFromSessionStorage = sessionStorage.getItem('key');
// Removing data
localStorage.removeItem('key');
sessionStorage.removeItem('key');
In summary, localStorage
is suitable for data that needs to persist across browser sessions, while sessionStorage
is suitable for data needed only within a single session.