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 Jan 20, 2025
Advertisement
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 👇👇
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.
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
// 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
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.
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.
// 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();
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 no expires
or max-age
option 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*60
means 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
;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.There are 2 primary places where Cookies are generally used
// 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)
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
More resources to understand JavaScript Local Storage & Session Storage
Advertisement
Advertisement
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.
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.
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
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.
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.
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.
© 2024 FrontendGeek. All rights reserved