Cookies vs Local Storage vs Session Storage

Photo by Bram Naus on Unsplash

Cookies vs Local Storage vs Session Storage

In detailed Cookies vs Local Storage vs Session Storage with differences

ยท

2 min read

Cookies

Cookies are data, stored in small text files, on your computer.

// Create a Cookie with JavaScript
document.cookie = "username=Manthan Ankolekar";
// With expiry date (in UTC time)
document.cookie = "username=Manthan Ankolekar; expires=Thu, 28 Apr 2013 12:00:00 UTC";
// With a path parameter
document.cookie = "username=Manthan Ankolekar; expires=Thu, 28 Apr 2013 12:00:00 UTC; path=/";
// Read a Cookie with JavaScript
let data = document.cookie;
// Change a Cookie with JavaScript
document.cookie = "username=Manthan Ank; expires=Thu, 28 Apr 2013 12:00:00 UTC; path=/";
// Delete a Cookie with JavaScript
document.cookie = "username=; expires=Thu, 28 Apr 2013 12:00:00 UTC; path=/";

Local Storage

Local storage object let you store key/value pairs in the browser. Syntax -

window.localStorage
// or
localStorage
// Save Data to Local Storage
localStorage.setItem(key, value);
// Read Data from Local Storage
let data = localStorage.getItem(key);
// Remove Data from Local Storage
localStorage.removeItem(key);
// Remove All (Clear Local Storage)
localStorage.clear();

Session Storage

Session storage object allows you to save key/value pairs in the browser. Syntax -

window.sessionStorage
// or
sessionStorage
// Save Data to Session Storage
sessionStorage.setItem("key", "value");
// Read Data from Session Storage
let data = sessionStorage.getItem("key");
// Remove Data from Session Storage
sessionStorage.removeItem("key");
// Remove All (Clear Session Storage)
sessionStorage.clear();

Difference between Cookies vs Local Storage vs Sesssion Storage

CookiesLocal StorageSession Storage
Stoage Capacity4kb10mb5mb
Browser SupportHTML4/HTML5HTML5HTML5
AccessibilityAny Browser WindowAny Browser WindowSame Browser Tab
ExpiryCan set ManuallyNeverOn Browser Tab Closes
Stored InBrowser & ServerBrowser OnlyBrowser Only
Sent with requestsYesNoNo
Supported Data TypesStrings OnlyStrings OnlyStrings Only
Auto ExpiryYesNoYes
Edit/blockYesYesYes
SSL SupportYesNoNo
ย