Session Storage vs Local Storage vs Cookie

bogicevic7

Dragoljub Bogićević

Posted on February 24, 2020

Session Storage vs Local Storage vs Cookie

The main purpose of this post is to give you a brief overview of these features:

Session storage

  • 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
  • can only be read on client-side
  • storage limit is about 5MB
  • opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window
// Write
sessionStorage.setItem('key', 'value');

// Read
let data = sessionStorage.getItem('key');

// Delete
sessionStorage.removeItem('key');

// Delete all
sessionStorage.clear();

Local storage

  • stores data with no expiration date
  • storage limit is about 5MB
  • data is never transferred to the server

Cons:

  • plaintext, hence not secure by design
  • limited to string data, hence need to be serialized = can not be used by web workers
  • XSS
  • can only be read on client-side
// Write
localStorage.setItem('key', 'value');

// Read
let data = localStorage.getItem('key');

// Delete
localStorage.removeItem('key');

// Delete all
localStorage.clear();

Cookie

  • stores data with expiration date
  • storage limit is about 4KB
  • cookie is sent to the server with each request
  • can be read/write on client-side and server-side (if the cookie is marked as HttpOnly than it is inaccessible to client-side scripts)
// Write
document.cookie = "key=value";

// Read
let x = document.cookie;

// Update
document.cookie = "key=new value";

// Delete - for deletion you should set expiration parameter to past date
document.cookie = "expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
💖 💪 🙅 🚩
bogicevic7
Dragoljub Bogićević

Posted on February 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Session Storage vs Local Storage vs Cookie
javascript Session Storage vs Local Storage vs Cookie

February 24, 2020