Explain the difference between cookies, session and local storage

Technology CommunityCategory: HTML5Explain the difference between cookies, session and local storage
VietMX Staff asked 3 years ago

Cookies

  • Limited storage space 4096 bytes / ~4 kb
  • Only allow to store data as strings
  • Stored data is sent back to server on every HTTP request such as HTML, CSS, Images etc,
  • Can store only 20 cookies per domain
  • In total 300 cookies are allowed on a site
  • Setting HTTP only flag will prevent accessing cookies via javascript
  • Can set expiration duration for auto deletion (can be set either from server or client)

Example:

// Set with expiration & path
document.cookie = "name=Gokul; expires=Thu, 18 Dec 2016 12:00:00 UTC; path=/;";

// Get
document.cookie;

// Delete by setting empty value and same path
document.cookie = "name=; expires=Thu, 18 Dec 2016 12:00:00 UTC; path=/;";

Session Storage

  • Storage space is 5 mb / ~5120 kb
  • Storage space may vary a little based on the browser
  • Only allow to store data as strings
  • Data is available per window or tab
  • Once window or tab is closed stored data is deleted
  • Data will be only available on same origin

Example:

// Set
sessionStorage.setItem("name", "gokul");

// Get
sessionStorage.getItem("name"); // gokul

// Delete
sessionStorage.removeItem("name"); 

// Delete All
sessionStorage.clear();

Local Storage

  • Storage space is 5 mb / ~5120 kb
  • Storage space may vary a little based on the browser
  • Only allow to store data as strings
  • Data will be only available on same origin
  • Data is persistant (untill explicitly deleted)
  • API is similar to session storage

Example:

// Set
localStorage.setItem("name", "gokul");

// Get
localStorage.getItem("name"); // gokul

// Delete
localStorage.removeItem("name"); 

// Delete All
localStorage.clear();