Item | Cookie | Local storage | Session storage |
---|---|---|---|
location | Browser | Browser | Browser |
data type | string | string | string |
expiration date | can set | semipermanent | until close session/tab |
capacity | 4KB | 5-10MB (depends on browser) | 5-10MB (depends on browser) |
send data to server | yes | no | no |
language | server-side script(mainly) | js | js |
Web Storage = Local storage + Session storage
As you can see, Local storage and Session storage are very similar, but there is one big difference.
That is expiration data
LocalStorage can keep data until deleting it which means if a user closes a tab, still js code can use LocalStorage data. This sounds useful, but need to select the right data type.
data persistence
LocalStorage
: will keep until users delete(probably delete cache) or the app remove/clear
SessionStorage
: will keep until users close tab/window or the app remove/clear
Cookie
: will keep until expires, users delete cookies or the app remove/clear
In terms of Cookie, we need to take care of each browser and time sync between client and server.
As you can see, 2 big differences are data size and sending data to the server.
How to use Local storage
set value
localStorage.setItem('myDogName', 'Ral');
// we can store json
localStorage.setItem('dogs', JSON.stringify(dogData));
get value
const myDog = localStorage.getItem('myDogName');
// of course, we can get data as json
const dogData = JSON.parse(localStorage.getItem('dogs'));
remove value
localStorage.removeItem('myDogName');
clear
this removes all data from localStorage
localStorage.clear();
How to use Session storage
In this article, I'm using js instead of backend scripts.
set value
sessionStorage.setItem('myDogName', 'Ral');
get value
const myDog = sessionStorage.getItem('myDogName');
remove value
sessionStorage.removeItem('myDogName');
clear
this removes all data from sessionStorage
sessionStorage.clear();
How to use Cookie
set value
document.cookie = 'my dog name was Ral'
get value
const data = document.cookie.split(':');
for(const elm of data) {
const content = elm.split('=');
console.log(content[1]);
}
set expiration
document.cookie = 'name="removed immediately"; max-age=0';
console.log(document.cookie);
// set 100 seconds
document.cookie = 'name="removed immediately"; max-age=0';
console.log(document.cookie);
other options
https://javascript.info/cookie#path
cookies with nodejs
https://www.geeksforgeeks.org/http-cookies-in-node-js/
Top comments (2)
Good article!
Just a couple of feedback items,
Probably could've explained data persistance a bit more - especially for sessionStorage
Could've also expalined the security aspects of all 3 storage methods and what kind of data is typically stored in these individual APIs in real-world scenarios.
@painotpi , thank you for your feedback.
just added some information on data persistence.