Cookies vs LocalStorage vs SessionStorage

Cookies vs LocalStorage vs SessionStorage

A brief Comparision of different web storage.

Introduction

Cookies have been there for a long time. They are helpful for storing stateful elements like auth tokens and user interaction habits on the website. Then, HTML5 introduced LocalStorage & SessionStorage, which gave much larger storage capacity and much more.

Similarities

  • All Three are stored on the User's browser.
  • They are Browser Independent, Something stored in Google chrome's LocalStorage won't be reflected in Firefox's LocalStorage.
  • Users do not share Cookies or LocalStorage between the user. For instance, if a user sets a LocalStorage, none of the other users will see that because it's stored in the user's computer.

comparison-table-cookie-ls.png

Space Comparision

  • Cookies: 4kb. Kept small as it is sent back & forth to the server, to reduce server load.
  • LocalStorage: 10Mb
  • SessionStorage: 5Mb

Accessibility:

  • Cookies and LocalStorage is available from any window on the specific browser.
  • SessionStorage is available in the single tab in which it was set.

Expiration:

  • Cookies: We have to manually set an expiration date/time.
  • LocalStorage: It never expires until deleted manually.
  • SessionStorage: When the tab in which it is set is closed, it expires.

Storage & Request:

  • Cookies are stored in the browser and server both, whenever a user sends a request, cookies are sent along to the server. That's why it has low storage so that there isn't much server load.
  • LocalStorage & SessionStorage are stored only in the browser and are not sent with the user request to the server.

Use Cases:

  • Cookies to be used to store authentication tokens or keys about user interaction around the site, which has a very low storage value.
  • LocalStorage & SessionStorage to be used whenever the user has to store something on the browser only.

Conclusion:

These web storages have their pro and cons and are widely used in modern web development. Cookies are mostly used to store auth tokens and LocalStorage and SessionStorage are used to store basic stateful values for the website, which doesn't contain private information.

Thank You.