Using browser storage

Namito YokotaNamito Yokota
2 min read

There are 3 main storage options within the browser. Use the following information to decide which option to use for your use case.

Session Storage

Session storage is a browser storage only accessible through client-side JavaScript in which the data stored is automatically deleted when the user closes the browser tab or window.

Differences

  • Expiration: On tab close

  • Storage capacity: 5MB

  • Accessibility: Current tab

Code example

sessionStorage.setItem("firstName", "John");
sessionStorage.setItem("lastName", "Doe");
sessionStorage.getItem("firstName"); // John
localStorage.removeItem("firstName");

Local Storage

Local storage is a browser storage only accessible through client-side JavaScript in which the data persists in the browser’s memory upon page refresh or window/tab close.

Differences

  • Expiration: Never

  • Storage capacity: 10MB

  • Accessibility: Any window or tab

Code example

localStroage.setItem("firstName", "John");
localStroage.setItem("lastName", "Doe");
localStorage.getItem("firstName") // John
sessionStorage.removeItem("firstName");

Cookies

Cookies are another form of browser storage only accessible by the server and not by the client-side JavaScript. The data stored in cookies are persistent upon page refresh or window/tab close, until the expired date passes.

Differences

  • Expiration: Manually set

  • Storage capacity: 4KB

  • Accessibility: Any window or tab

Code example

document.cookie = "firstName=John; expires=${new Date(2025, 0, 1).toUTCString()}"; // 01-01-2025
document.cookie = "lastName=Doe; expires=${new Date(9999, 0, 1).toUTCString()}"; // Never expires
document.cookie // firstName=John; lastName=Doe
document.cookie = "firstName=; expires=Thu, 01 Jan 1970 00:00:00 GMT"
1
Subscribe to my newsletter

Read articles from Namito Yokota directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Namito Yokota
Namito Yokota