Websites hosted on a browser have no capacity of having any memory to store user's data. A user visiting from one page to another page on a website will be treated as a new user every time. The browser provides different types of storage mechanisms (localStorage, sessionStorage, cookies) to overcome this issue. Storage mechanism enables the website you are visiting to keep track of your movement from one page to another page so that the same information doesn't get asked which is already given to the website.
localStorage, sessionStorage, and cookies are all client storage solutions that store in a single file in the user's system. Session data is stored on the server where the application/website is hosted. localStorage and sessionStorage, part of the web storage API, are two awesome tools to save the data in format of key/value pairs locally.
In this article, We will try to understand the difference between localStorage and sessionStorage.
It is a type of web storage that allows websites/applications to store and access data in the browser with no expiration date. This means the data stored in the browser will persist even after the browser window has been closed.
// Save data to localStorage
// Get saved data from localStorage
let lastname = localStorage.getItem('key');
// Remove saved data from localStorage
// Remove all saved data from localStorage
The sessionStorage object stores data for only one session, Meaning the data is deleted when the browser tab is closed.
// Save data to sessionStorage
// Get saved data from sessionStorage
let lastname = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
// Remove all saved data from sessionStorage
The storage limit is the maximum amongst the three.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
It works on the same-origin policy. So, data stored will only be available on the same origin.
It stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
Data is never transferred to the server.
Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.
localStorage and sessionStorage are performing similar tasks but with some very basic differences.
This article was originally posted over JsonWorld