DEV Community

loading...

Session Storage vs Local Storage vs Cookie

Dragoljub Bogićević
202 Accepted
Updated on ・1 min read

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=/;";

Discussion (4)

Collapse
Sloan, the sloth mascot
Comment deleted
Collapse
bogicevic7 profile image
Dragoljub Bogićević Author

Well not exactly, the post is about session storage, local storage and cookies... It is like brief overview of the features and differences, the post is not about client-side storage.

Collapse
javierpomachagua profile image
Javier Pomachagua

If I'm building a Nuxt Client with a Net Core backend.
Should I use cookies for storaging token?

Collapse
bogicevic7 profile image
Dragoljub Bogićević Author

I do not know, using cookies even with HttpOnly and secure flags are still vulnerable to XSS and CSRF...