There are many places over the internet which describe and explain this in details. I thought to gather few of them into one place.
Local Storage
- This is a part of the web storage API.
- Store data as key value pairs.
- Can share between sub domains.
- Store data in user’s browser and can be inspected by developer tools.
- Large amounts of data can be stored locally, without affecting website performance.
- Information will never transferred into the server.
- From all pages can store and access data.
- Support up to 10MB storage for most of modern browsers.
- No expiration.
// Save data into local storage
let key = 'Key 1';
localStorage.setItem(key, 'damith');
// Get data from local storage
let myItem = localStorage.getItem(key);
// Update excising value
localStorage.setItem(key, 'damithw');
// Remove key from local storage
localStorage.removeItem(key);
// Clear all local storage data for current origin
localStorage.clear();
Session Storage
- This is a part of the web storage API.
- Store data as key value pairs.
- Get cleared after page session ends.
- Opening page in different tab or window cause a new session to be initiated.
- Information will never transferred into the server.
- Support up to 10MB storage for most of modern browsers.
- Expire after browser or tab closed.
// Save data to sessionStorage
sessionStorage.setItem('name', 'damith');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('name');
// Remove saved data from sessionStorage
sessionStorage.removeItem('name');
// Remove all saved data from sessionStorage
sessionStorage.clear();
Cookies
- We can set expiration period to each cookie
- The browser may store it and send it back with the next request to the same server
- Keep stateful information for the stateless HTTP protocol. ( Ex: User logged-in )
- Mainly used for
- Session management – Logins, shopping carts
- Personalization – Themes, User preferences
- Tracking – Recording and analyzing user behavior
- Stored in client’s browser
- Sent with every request
- Two types of cookies are
- Session cookies – It is deleted when client shut down
- Permanent cookies – Can have expiry date
- Domain and path directives define the scope of the cookie
- Should consider about Session hijacking and XSS
For more information please refer below source urls
https://www.w3schools.com/Html/html5_webstorage.asp
https://www.html5rocks.com/en/tutorials/offline/quota-research/
https://alligator.io/js/introduction-localstorage-sessionstorage/
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies