Describe the difference between a localStorage, sessionStorage and cookie.

All the above-mentioned technologies are key-value storage mechanisms on the client side. They are only able to store values as strings.

Describe the difference between a localStorage, sessionStorage and cookie. (Cont...)

localStorage is a way to store data on the client’s computer. It allows the saving of key/value pairs in a web browser and it stores data with no expiration date.

localStorage can only be accessed via JavaScript, and HTML5. However, the user has the ability to clear the browser data/cache to erase all localStorage data.

LocalStorage:

Describe the difference between a localStorage, sessionStorage and cookie. (Cont...)

  • 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 5-10MB
  • opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window

 

Same as localstorage , we can write key-value pair in session storage as well.

SessionStorage:

Describe the difference between a localStorage, sessionStorage and cookie. (Cont...)

  • Stores data that has to be sent back to the server with subsequent XHR requests. Its expiration varies based on the type and the expiration duration can be set from either server-side or client-side.
  • Cookies are primarily for server-side reading (can also be read on client-side), localStorage and sessionStorage can only be read on client-side.
  • Size must be less than 4KB.
  • Cookies can be made secure by setting the httpOnly flag as true for that cookie. This prevents client-side access to that cookie.

Cookie:

Describe the difference between a localStorage, sessionStorage and cookie. (Cont...)

cookie localStorage sessionStorage
Initiator Client or server. Server can use Set-Cookie header Client Client
Expiry Manually set Forever On tab close
Persistent across browser sessions Depends on whether expiration is set Yes No
Sent to server with every HTTP request Cookies are automatically being sent via Cookie header No No
Capacity (per domain) 4kb 5MB 5MB
Accessibility Any window Any window Same tab

Describe the difference between a localStorage, sessionStorage and cookie. (Cont...)

Note: If the user decides to clear browsing data via whatever mechanism provided by the browser, this will clear out any cookie, localStorage, or sessionStorage stored.

 

It's important to keep this in mind when designing for local persistance, especially when comparing to alternatives such as server side storing in a database or similar (which of course will persist despite user actions).

Made with Slides.com