Cookies vs Local Storage vs Session Storage

BhanuBhanu
2 min read

Browser storage is important from as frontend developer aspect. They are extensively used for storage cookie values, session details etc. Browser storage is specific to one browser i.e. you cannot access storage values of one browser from another.

Here is a brief difference between them

Browser storage: Local Storage, Session Storage, Cookie, IndexedDB and  WebSQL | by Jallen Liao | Medium

Cookies 🍪

cookies are best for authentication perpose from developer's perspective. They have very short storage about "4kb", can be accessible from any window of the browser and expire after a certain time period. Cookies are get deleted or removed after their expiration date exceed or deleted manually. They don't get delete on tab close or browser close. You should store values in cookie storage only if you have an aspect to send them to server else local or session storage is good.

Some quick methods in JavaScript

set a cookie => document.cookie = "cookie_name=cookie_value"
get a cookie => JS doesn't have in built method for getting cookie value, but you can implement your own like,
const getCookie = (cname)=> {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
delete a cookie => to delete a cookie just set the cookie to a previous date e.g.
document.cookie = "cookie_name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Local Storage

Local storage is browser only storage, has "10mb" storage capacity which highest among session and cookie storage. Local storage is generally used to store the data that meant only for browser. Local storage data can be accessible from any window of the browser and they never expire.

Some quick methods in JavaScript

set a value => localStorage.setItem('name', 'value')
get a value => localStorage.setItem('name')
delete a value\=> localStorage.removeItem('name')

Session Storage

Session storage works exactly same as Browser storage but it has "5mb" storage capacity. Session storage data can be accessible from any window of the browser and they expire on tab close. Session storage is generally used to storage data like for an payment session etc.

Some quick methods in JavaScript

set a value => sessionStorage.setItem('name', 'value')
get a value => sessionStorage.setItem('name')
delete a value\=> sessionStorage.removeItem('name')

That's all about the Browser's storage. Happy learning.

If found this helpful please like and comment.

0
Subscribe to my newsletter

Read articles from Bhanu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bhanu
Bhanu