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.
Anuj Sharma
Last Updated Feb 6, 2026

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
- Understand JavaScript Local Storage
- Understand JavaScript Session Storage
- Understand JavaScript Cookies
- 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
- Store Personalization Configurations like Light/Dark Mode settings
- 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
;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.;expires=<Date in UTC string format>- Add the expiry of the cookie when it will be removed by the browser. If there are noexpiresormax-ageoption mentioned cookie will expire at the end of the page session.;max-age=<max age in sec>- It is the maximum age of the cookie in sec for example;max-age=60*60means the cookie will expire in 1 hour.;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- ";samesite=lax" means this cookie can be sent to all same-site requests.
- ";samesite=strict" means this cookie can't be sent with same-site or cross-site requests.
- ";samesite=none" means there is no restriction on the cookie to send with same-site or cross-site.
;secure- It specifies that the cookie can be transferred to the secure protocol (HTTPS);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
- 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.
- 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)
📌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
A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me 🚀
Learn Next
Comments
Be the first to share your thoughts!
No comments yet.
Start the conversation!
Share your expertise
Publish a blog or quick notes on topics you know well — your write-up could be the answer someone needs before their next frontend interview.
Build your portfolio
Help the community
Sharpen your skills
Earn goodies
Other Related Blogs
How does JWT (JSON Web Token) Authentication work - Pros & Cons
Frontendgeek
Last Updated Jun 15, 2026
Understand the JWT(JSON Web Token) and how JWT decode works. It also covers how the end-to-end JWT authentication works between client & server, along with the pros and cons of using JWT.
What is CORS ? Cross-Origin Resource Sharing Explained [For Interviews]
Anuj Sharma
Last Updated Feb 6, 2026
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.
Part 1: From Zero to Published — How I Built and Published My First React NPM Package
Akash Deep Chitransh
Last Updated Feb 6, 2026
Learn how to build and publish your own NPM package with Rollup, testing, and troubleshooting. Stay tuned for part 2: building a React state management library!
Understanding Critical Rendering Path (CRP) to Improve Web Performance
Anuj Sharma
Last Updated Feb 6, 2026
Understand what all steps are involved in the Critical Rendering Path (CRP) and how optimization of different steps can improve the overall web-vitals of a web application
What happens when you type google.com in the browser
Anuj Sharma
Last Updated Feb 5, 2026
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.
Boost Your Site Speed with CSS Sprites: A Practical Guide
Vaibhav Kumar
Last Updated Jan 28, 2026
Master CSS sprites to slash HTTP requests, supercharge load times, and optimize icons—practical guide with code, tools, and 2026 best practices.
Explained Web Authorization Techniques - Session & JWT
Anuj Sharma
Last Updated Dec 16, 2025
Understand important web authorization techniques to enhance role-based authentication for any web application with popular techniques like Session & JSON Web Token (JWT)
