Blog/NotesConcept

Understand JavaScript Local Storage, Session Storage and Cookies

Explore how to create and use javascript local storage, session storage and cookies. Explore the key differences between Local Storage vs Session Storage vs Cookies to understand the trade-offs.

Intermediate

Anuj Sharma

Last Updated Jan 20, 2025


Advertisement

JavaScript Local Storage, Session Storage & Cookies - FrontendGeek

Storing data in the client-side browser is a common case to provide personalized user experiences with the web application and JavaScript local storage, session storage, and cookies are the most common ways to store the data in these cases.

There are certain differences between these storage mechanisms and understanding these differences is important to choose the best-suited one for the web application. This post covers the implementation, usage and differences to help you to choose among these Let's jump 👇👇

📒Table of content

  1. Understand JavaScript Local Storage
  2. Understand JavaScript Session Storage
  3. Understand JavaScript Cookies
  4. Key Differences Between Local Storage Vs Session Storage Vs Cookies

📌Understand JavaScript Local Storage

Browser provides localStorage as a read-only property as part of the window object (in the browser only). This localStorage property allows to access the Storage Interface, which can be used to set and get the data from the browser's Local Storage.

Data stored in local storage can be accessible across the tabs for the same domain and it persists even after closing the tabs. There is no expiry associated with the localStorage. (** browser deletes local storage used as part of incognito mode as soon as the incognito tab is closed)

Local storage only allows to store UTF-16 String format as part of the storage, and binary data can't be stored in the local storage. 

It's important to note that localStorage provides access to the local storage associated with the Document's Origin (Protocol + Domain + Port), and each domain has its localStorage property which provides access to the Document's Origin Storage.

When to use Local Storage?

JavaScript Local Storage is best suited for scenarios where you want to store the key-value pair of the application state in a persistent way using UTF-16 string. Where your application needs to store the data which can be accessed across the tab sessions.

Here are the most common scenarios for using a browser's Local Storage 

  1. Store Personalization Configurations like Light/Dark Mode settings
  2. Store Authorization Tokens like JWT authorization tokens. 

Example Code:

// Adding data to the local storage
localStorage.setItem("mode", "light");

// Access data from local storage
const mode = localStorage.getItem("mode");

// Modify data to the local storage 
localStorage.setItem("mode", "dark")

// Delete data from local storage
localStorage.removeItem("mode");

// Delete all local storage
localStorage.clear();

You can also check out the Live example provided by MDN - Local Storage Example 

📌Understand JavaScript Session Storage

Similar to localStorage, the browser also provides a read-only sessionStorage property as part of the window object. sessionStorage is used to access the session Storage Object associated with the Page Session.

Browser creates a new page session every time for the loaded document in the new tab. Every tab has its own page session, and copying the URL in another tab will access the session storage associated with that Tab's page session only.

Unlike local storage, session storage comes with expiry and the data stored in session storage is accessible for the current page session only. As soon as the page session expires (When the tab is closed) the browser removes all the data from the session storage associated with the page session.

💡Note: When a new duplicated tab is created then session storage also copied from one tab to another tab.

When to use Session Storage?

As the name suggested, session storage is primarily used to maintain the parameters associated with the user session after certain authentication. These params stored as part of session storage can be used until the session is maintained.

One of the common examples of using session storage is to store the role of the user after authentication which can be accessible throughout the session and provides Role-based access to the application (RBAC). It means if the user has a "viewer" role in the session then it can access the read-only part of the application.

Example Code:

// Set data to sessionStorage
sessionStorage.setItem("role", "viewer");

// Get saved data from sessionStorage
const role = sessionStorage.getItem("role");

// Remove saved data from sessionStorage
sessionStorage.removeItem("role");

// Remove all saved data from sessionStorage
sessionStorage.clear();

📌Understand JavaScript Cookies

Cookies are small pieces of information generally sent by the servers to the client so that when the user hits the server again, the server can get some information about the client. It is generally used to track the user's activity to visit the particular domain and for other analytical purposes. It also plays an important role in enabling basic authentication to web applications.

In JavaScript, cookie is a property of the document, which allows you to set or get cookies associated with the document. document.cookie provides a list of all the cookies in the form of key=value pairs separated by ; .

A single cookie can be set to the document by assigning the cookie in a string format to document.cookie  like document.cookie = <cookie string>. There are multiple cookie options are also available that can also be set along with the cookie separated by ;.

// Set cookie with options
document.cookie = "activity=website_visit; max-age=60*60; secure"

Here is the list of the most common cookie options

  1. ;domain=<domain> - It can contain the host of the document for which this cookie is sent if not specified then the host of the current document is used by default.
  2. ;expires=<Date in UTC string format> - Add the expiry of the cookie when it will be removed by the browser. If there are no expires or max-age option mentioned cookie will expire at the end of the page session.
  3. ;max-age=<max age in sec> - It is the maximum age of the cookie in sec for example ;max-age=60*60 means the cookie will expire in 1 hour.
  4. ;samesite - This cookie option is used by the server as part of set-cookie header, to specify the same site policy for the cookie. This can have 3 possible values
    1. ";samesite=lax" means this cookie can be sent to all same-site requests. 
    2. ";samesite=strict" means this cookie can't be sent with same-site or cross-site requests.
    3. ";samesite=none" means there is no restriction on the cookie to send with same-site or cross-site.
  5. ;secure - It specifies that the cookie can be transferred to the secure protocol (HTTPS)
  6. ;httponly - This option is used by the server while setting up the cookies on the client side as part of the Set-Cookie header, this ensures that the client-side application can't get access to this cookie to prevent any modification.

When to use Cookies?

There are 2 primary places where Cookies are generally used

  1. Basic Authentications (user/password)- In the case of basic authentication, the server uses "set-cookie" to set the token information as part of the cookie that can be sent later in the subsequent API calls.
  2. Tracking user activities - Some of the servers set cookies to the client's browser to track the usage pattern of the client like website visits or login frequency.

Example Code:

// Set / Add a single cookie
document.cookie = "activity=revisit; max-age=60*60*24; secure";

// Get all cookies, Run in the browser console.
console.log("All cookies = ", document.cookie)

Cookies in browser console

📌Key Differences Between Local Storage Vs Session Storage Vs Cookies

Here are the major differences between these web storage mechanisms 

Comparison Parameter Local Storage Session Storage Cookies
Content Type UFT-16 Strings Format (Stringify Objects) UFT-16 Strings Format (Stringify Objects) "Key-value" pair
Expiration No expiration (Explicitly deleted) Expiry of Page session (Tab Closed) Depends on expires & max-age options
Max-Size 5-10 MB per domain** 5 MB per domain** 4 KB per cookie
Access in Web Workers Not accessible Not accessible Not accessible
Primary usage User preferences, Application state User session related params like role Auth Tokens, tracking params

** Can vary depending on the browser

⏩Next, Read

More resources to understand JavaScript Local Storage & Session Storage

 

Advertisement

Advertisement


Share this post now:

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Other Related Blogs

What is javascript:void(0) and How it Works?

Anuj Sharma

Last Updated Jan 5, 2025

A comprehensive explanation about using javascript:void(0) in javascript. When to use javascript:void(0) and how it works with examples of using it with anchor tag.

Understand JavaScript Date Object with Examples (for JavaScript Interviews)

Anuj Sharma

Last Updated Jan 9, 2025

Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.

HTTP/2 vs HTTP/1.1: What's the Key Difference?

Anuj Sharma

Last Updated Jan 29, 2025

Understand the difference between HTTP/2 vs HTTP/1.1 based on the various parameters, which helps to understand the improvement areas of HTTP/2 over HTTP 1.1

What happens when you type google.com in the browser

Anuj Sharma

Last Updated Feb 13, 2025

Details about how the browser works behind the scenes and what happens when you type google.com in the browser, starting from communication to the webpage rendering.

Promise Polyfill in JavaScript - Step by Step Explanation

Anuj Sharma

Last Updated Jan 28, 2025

An Interview-focused explanation of Promise Polyfill in JavaScript which helps to understand both Functional and ES6 custom promise implementation.

What is CORS ? Cross-Origin Resource Sharing Explained [For Interviews]

Anuj Sharma

Last Updated Dec 10, 2024

A brief explanation of Cross-Origin Resource Sharing (CORS) concept to enable client application accessing resources from cross domain and HTTP headers involved to enable resource access.

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved