JavaScript — All About Local Storage, Session Storage, and Cookies

What are the advantages and disadvantages of localStorage, sessionStorage, session, and cookies from a technological standpoint, and when should we utilize one over the other?

What is Client-side storage?

Client-side storage, as the name implies, allows the user to store data on the client (i.e. the user’s browser). And Server-side storage, on the other hand, keeps data on the server (i.e. an external database).

The image is taken from Wikimedia

When does it come in handy?

The following use scenarios may benefit from client-side storage:

  • User preferences can be saved (i.e. font size, theme, etc.)
  • Save the previous activity’s session (i.e. auth token, user details, shopping cart, etc.)

Client-Side Storage Types

Here are types of client-side storage-

  1. Local Storage
  2. Session Storage
  3. Indexed DB

1. What is the localStorage?

Where we find this stored data

Web storage data is saved in an SQLite file in a subdirectory in the user’s profile in Google Chrome. On Windows PCs, the subdirectory is stored at \AppData\Local\Google\Chrome\User Data\Default\Local Storage whereas, on macOS, it is found at ~/Library/Application Support/Google/Chrome/Default/Local Storage.

Methods for adding and removing data from Local Storage

There are five different ways to use localStorage in your web applications:

localStorage.setItem('Key', 'value')
localStorage.clear() // Clear all localStorage
localStorage.key() // Pass a number to retrieve the key of a localStorage
Object.keys(localStorage); find all keys

2. What is Session Storage?

The Session Storage saves data in the form of Keys and Values for a single session. When the browser is closed, the data stored in Session Storage will be removed.

Methods for adding and removing data from session storage

sessionStorage.setItem('Key', 'Value') // Save data to sessionStorage
sessionStorage.getItem('Key') // Get saved data from sessionStorage
sessionStorage.removeItem('Key') // Remove saved data from sessionStorage
sessionStorage.clear() // Remove all saved data from sessionStorage

Local Storage vs Session Storage

  • The browser data is cleared by the user.

3. Cookies

Image Source Unsplash
document.cookie = 'username=Gyanendra'
document.cookie = 'username=Gyanendra; expires=any upcoming date and time; path=/'
document.cookie = 'username=Gyanendra; expires=passed date and time; path=/;'



Full Stack developer & Technical writer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store