We all know that for client and server communication HTTP protocol is used. But this protocol is stateless means it doesn't track any response by the server or request by the client. To resolve this problem, cookies, localStorage & sessionStorage come into picture to manage and track data between client-server requests.

localStorage and sessionStorage both are part of Web Storage API provided by browser and introduced in HTML5 to store the data in client-side computer.
Cookie are not a part of web storage API as they were introduced way before web storage API. They are used in both client and server side communication.

We will see each one of behaviors, when to use with example.

1) Cookie

  • cookies are small piece of plain text data to remember/ persist user's information across sessions on the web.
  • They are sent to server with each request so that server can identify particular user is authenticated user or not and provide personalized content to him/ her.
  • They can storage 4KB of data per cookie means can store small amount of data.
  • They are typically used for authentication, session management, storing login status, user preferences and tracking user's behavior on the site.
  • They can be set to expire at a specific period of time or can be deleted manually.
  • They can be accessed by other domains that user visits without user consent. This is the main concern by cookie. We can't store sensitive data in the cookie. Yes we can use HttpOnly, Secure, and Expires/Max-Age attributes that cookies provide to prevent/ leakage of the user's information in the web.
  • Cookies doesn't expire on closing the browser but will expire at a specific date (Expires) or length of time (Max-Age) .
  • Mainly suitable for client-server communication

Example - When user login for the first time, the server can create a cookie to remember their username, unique session_ID etc. If the user visits the same website again in future, the browser sends the cookie back to the server with every request. The server can then use the information in the cookie to identify the user and personalize their experience on the site. But here whenever user sends request to server, api call is made and it costs a lot. Some user will experience a significant delay if network is slow.

//setting cookie
document.cookie = "username=John; expires=Fri, 31 Dec 2025 12:00:00 UTC;

2) localStorage

  • stores data in key-value pairs as string in user's browser.
  • here data persists even after user closes their browser tab/ window or on page reloades/ refreshes/ reopend. Means it doesn't have expiry date. It remains until user explicitly remove the data through code or clearing by double clicking on that data in Application tab of browser developer tool or by clearing browser's cache.
  • We can access localstorage data in multiple tabs, different windows if it has the same url.
  • It can store data upto 5MB or 10MB depending on the browser.
  • Its data is never transferred to the server but you can manually include its value in fetch request.
  • It is synchronous. If I perform operations on localStorage, It will block the execution of other javascript code until the current operation will get completed.
  • It follows same origin policy (per-origin) means http://abc.com’s localStorage object is different from https://blog.abc.com’s localStorage object because the two origins use different protocols (http and https), different hosts (abc and blog.abc). So data will be different for these two sites.
  • localStorage is a property of the global Window object. Therefore, localStorage.setItem() is equivalent to window.localStorage.setItem().
  • Use localStorage when you need to store simple, persistent data on a user's device for a longer period of time.

Methods of localStorage

// Save data
localStorage.setItem("key", "value");

localStorage.setItem("username", "Alice");

// Retrieve data
localStorage.getItem("key");

localStorage.getItem("username")
console.log(username)

// Remove data
localStorage.removeItem("key");

localStorage.removeItem("username");

// Clear all data from localStorage
localStorage.clear();

If I store same key with different value, then data will be override with the previous ones and get new value as result.

localStorage.setItem("username", "Alice");
localStorage.setItem("username", "John");

localStorage.getItem("username")
//output - John

The removeItem() method will do nothing if its key does not exist in the local storage. You will get output as undefind.

localStorage.removeItem("username");
//output - undefined

And getItem() method will return null if its key doesn't exist and I try to access that key, it will return null.

localStorage.getItem("username");
//output - null

We can store data as string in localStorage, but what if I want to store object in it. If I do below like this, it will return "[object Object]".

localStorage.setItem("user", {"name": "Alice"});

We need to convert object into string before storing it into localStorage by using JSON.stringify()

const user = {"name": "Alice"}
localStorage.setItem("User", JSON.stringify(user));

And to get the object data from localStorage, again we need to convert string to its original form by using JSON.parse()

JSON.parse(localStorage.getItem("User")))

Usage:

  • You can use it to create and store notes in user's computer
  • most suitable for user preferences data like theme, layout or language settings that doesn't need to be sent to server
  • to store form inputs so users don’t lose data when they refresh the page.
  • to keep user authentication tokens for faster login whenever visit the website next time.

Example:- When login in social media application or e-commerce website, your login credentials like username, password (same for longer period of time) gets stored in localStorage. So every time you come back, application doesn't require to make api call to get account details & retrieve data from it. It helps to save api call.

3) sessionStorage

It does almost the same work, has the same methods like localStorage but with a few minor differences mentioned below: -

  • sessionStorage stores the data temporarily as string in key-value pairs in client side but for a single/ current session/ when a tab is open.
  • It's data gets cleared when user closes the tab/ window/ page session ends/ refreshes that page. i.e. it follows per-instance policy plus same origin policy.
  • Here browser creates unique page session with each tab/ window. Hence it creates new instance/ object of sessionStorage for an app without interfering other instances of the same app.
  • It can store 5MB of data means it has a higher storage capacity compared to cookies.
  • It's useful for storing temporary data that is needed when user is on that website like session-based authentication details that shouldn't persist beyond the current session.
  • To store large amount of data, use database instead.

Methods of sessionStorage

// Save data
sessionStorage.setItem("username", "John");

// Retrieve data
let username = sessionStorage.getItem("username");

// Remove data
sessionStorage.removeItem("username");

// Clear all data
sessionStorage.clear();

Usage:

  • to store authentication tokens for a single session
  • to store user's input in multi-step form. In this case user need that input data for that session only and don't want to lose it when switching between pages.

Tricky Question

Q) Is there any way you can persist sessionStorage data for a longer period of time?
Ans - Yes. We can set manual expiration time in it.

let now = new Date().getTime();
let expiry = now + 1000 * 60 * 30; // Expires in 30 minutes
sessionStorage.setItem("expiryTime", expiry);

Differences and similarity between cookie, localStorage and sessionStorage

cookie localStorage sessionStorage
data accessible any window any window same tab
data persistence depends on expires/ max-age attribute data persists even after closing the session data is lost when session is over
storage capacity 4KB of storage 5-10MB per origin depends on browser 5MB per origin
expire manually set using expires attribute till explicitly delete by code/ user when session ends/ explicitly delete by code/ user
data transfer to server yes no no
can read and write data client and server client client
accessible in domain/ origin different same same
supported by all browsers including older ones yes yes yes
web storage api (introduced in html5) no yes yes
synchronous yes yes yes
property of window object indirectly (window.document.cookie) yes yes
usage for client-server communication for data that doesn't need to be sent to server for storing session-relevant data