What is the difference between localStorage, sessionStorage and cookies?

· · 474 views · Solved

What are the specialized upsides and downsides of localStorage, sessionStorage, and cookies, and when might I use one over the other?

0
2 Answers

LocalStorage as it's called, it's local storage for the browsers, it can save up to 10MB, SessionStorage does likewise, yet as its name saying, it's session based and will be deleted after closing your browser, additionally can store less then LocalStorage, as up to 5MB. However Cookies are extremely small data storing in the browser, that can save up 4KB and can be accessed to through server or browser both.

0
Best answer

1. LocalStorage

Pros:

  • Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
  • The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
  • The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

Cons:

  • It works on same-origin policy. So, data stored will only be available on the same origin.

2. Cookies

Pros:

  • Compared to others, there's nothing AFAIK.

Cons:

  • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
  • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server. Typically, the following are allowed:
    • 300 cookies in total
    • 4096 bytes per cookie
    • 20 cookies per domain
    • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
    • sessionStorage

3. sessionStorage

Pros:

  • It is similar to localStorage.
  • The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.

Cons:

  • The data is available only inside the window/tab in which it was set.
  • Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.
0

Please login or create new account to participate in this conversation.