Oops! Something went wrong while submitting the form.
Difference between local storage, session storage, and cookies
Anom Warbhuvan
~ 9 min read | Published on May 25, 2023
In web development, the ability to store data on the client-side is an essential component of building robust and feature-rich web applications. With the introduction of HTML5, we have been given several options to store or cache information on the client browser, including cookies, local storage, and session storage. Each of these storage mechanisms has its own unique advantages and limitations, making it important to understand their differences.
In this article, we will help you understand how these storages work, their pros and cons, use cases, and compare local storage, session storage, and cookies against some standard parameters.
Web apps save data locally on the user's device using a browser feature called local storage. Local storage is usually in the form of key-value pairs, and is stored in the browser's memory. The key is a unique identifier, associated with a specific value, and is use to retrieve the related value.
This data can still be read and modified by the program even when the user closes the browser and opens it again later. Despite the similarities between local storage and cookies, there are a few significant variations.
Local storage is effective in reducing traffic over the network as it sends fewer requests to the server. Moreover, local storage has a bigger data storage capacity than session storage or cookies.
How does local storage work?
Local storage is implemented using the HTML5 standard's Web Storage API. Web Storage API provides localStorage and sessionStorage objects to perform operations on local storage.
Any page from the same domain may access persistent storage space provided by the localStorage object. Until it is manually deleted by the user or the program, data kept in localStorage is kept there eternally. Similar storage space is provided by the sessionStorage object, but the information is only accessible by the page that created it and is removed at the end of the browser session.
Take a look at code to know how a local storage can be used to store and retrieve data:
// Store data in local storage
localStorage.setItem('username', 'Anom');
localStorage.setItem('LogIn', true);
// Retrieve data from local storage
const username = localStorage.getItem('username');
const LogIn = localStorage.getItem('LogIn');
// Remove data from local storage
localStorage.removeItem('Anom');
console.log(username); // "Anom"
console.log(LogIn); // "true"
Advantages
Pros of Local Storage
Details
Persistent storage
Unlike session storage, which disappears when the browser is closed or the device is turned off, local storage allows developers to preserve data that may be used across multiple sessions and visits.
Large storage capacity
Local storage typically has a storage capacity between 5 and 10 MB per domain. In comparison to cookies or session storage, this enables developers to keep more data.
Faster access
Accessing local storage is quicker than sending a request to a distant server. By lowering the necessary network traffic, this can enhance the performance of online applications.
Better offline support
Even in poor network connectivity, data remains on the users device throughout the browser session.
Disadvantages
Cons of local storage
Details
Limited cross-domain access
One of the local storage limitation is that web applications on separate domains cannot access each other's data.
Security concerns
If you are wondering is local storage secure, that’s a genuine question. Cross-site scripting (XSS) attacks on local storage make it possible for bad guys to take data from a user's device.
No built-in expiration mechanism
If there is no expiration mechanism, then data might accumulate continuously resulting in too much consumption of storage space.
Storage capacity limitations
Data can build over time and fill up more capacity since local storage lacks an internal expiration mechanism, adding one more limitation to local storage.
Use cases
Here are some common use cases of local storage:
User preferences: Local storage can be used to keep track of user preferences, such as preferred languages, themes, or layouts. It offers users a better and more personalized experience across all devices.
Application cache: The web application stores frequently visited data and assets locally, using local storage as an application cache. This lowers the amount of network traffic needed to load the application.
Shopping cart: It allows users to add or remove where local storage can be utilized to keep the items in their shopping cart. Due to this, users will get a seamless shopping experience.
Offline access: Data that can be accessible even when the device is offline or has poor network connectivity might be stored in local storage.
Login state: User can save his/her login details in the local storage and stay logged in even if the browser is closed.
Session storage
What is session storage?
Web developers can keep data on a user's device for a single browsing session thanks to the session storage. Session storage is only available till the session is present, this means it will erase all the data after user exits the website.
We can say that it creates a temporary storage object which is scoped to the current browsing context and is not shared between different browser tabs or windows.
How does session storage work?
The window is available to web applications when they need to store data in session storage. The sessionStorage object provides a key-value store interface, just like local storage. The web application may establish values for specific keys in session storage while the user is browsing; these values may later be retrieved and modified.
Here is an example of how data can be stored and retrieved using session storage:
// Store data in session storage
sessionStorage.setItem('username', 'Anom');
sessionStorage.setItem('LogIn', true);
// Retrieve data from session storage
const username = sessionStorage.getItem('Anom');
const LogIn = sessionStorage.getItem('LogIn');
// Remove data from local storage
sessionStorage.removeItem('Anom');
console.log(username); // "Anom"
console.log(LogIn); // "true"
Advantages
Pros of session storage
Details
Security
Data gets stored for the duration of the session and is automatically removed when the session ends. Thus, session storage is secure for storing private information like session IDs or authentication tokens.
Temporary
Data on browsing session is temporarily stored using session storage. This can assist in clearing up space and minimizing clutter in the user's browser.
Easy to use
Developers may easily implement and use session storage in their online apps because to its straightforward API, which is comparable to local storage.
Disadvantages
Cons of Session storage
Details
Limited storage
Depending on the browser, session storage normally has a storage limit of 5 to 10 MB. This indicates that it might not be appropriate for large-scale data storage.
Session dependent
The data is destroyed when the session ends because session storage depends on the active browsing session. User can face a difficulty while accessing the data in succeeding sections.
Not shared
The scope of session storage is the current browsing context; it is not shared throughout tabs or windows. Data sharing between components of the same application or other applications may become challenging as a result.
Use cases
Here are some common use cases on when to use session storage:
Form data: Session storage is a good way to store data captured in a web form. This data can include user name, email address, phone number, or any other information website owner chooses to ask for.
User preferences: It allows developers to record user preferences, such as selected language, location, time zone, etc. through which you can create a personalized experience for your users.
Shopping cart: All the goods added to a shopping cart can be saved in session storage and at the time of navigating you can add or delete those goods. One more thing, when a user ends a browser session or completes a transaction, this data is removed.
Authentication tokens: Session storage, which saves authentication tokens or session IDs, allows the user to remain logged into the web application. After the user signs out or quits the browser, this data is removed.
Game state: The session storage can hold data related to user's game score, level, and even progress. Allowing them to pick up right from where they left the game or closed the browser.
Cookies
What are cookies?
When a user accesses a website, a web server generates small text files known as cookies, and the user then keeps these data on their device. Cookies are used to track user behavior, remember user preferences, and deliver customized web experiences.
A key-value pair and an expiration date are both part of a cookie. The value, which contains details about the user or their activity on the website, can be retrieved using the key, a special identifier. Cookies have expiration dates before being uninstalled from a device automatically.
How do cookies work?
The user visits a website for the first time. The website's server sends a cookie to the user's browser, which is stored on the user's device.
The user interacts with the website, such as logging in or adding items to a shopping cart. The website may use the cookie to remember the user's preferences or to keep the user logged in during their browsing session.
When a user visits website again, cookies are send back by the browser where server receives the information and uses it to customize the user experience.
Advantages
Pros of cookies
Details
Personalization
Cookies are be used to remember user preferences, like language or theme, of the website. This enables developers create a more personalized experience for end users.
Convenience
Developers can use it to simplify how users interact with the websites by saving things like login information or the contents of the shopping cart.
Performance
Helps in increasing page performance through data caching and reducing server queries.
Analytics
Cookies keep a track of user behavior and gather data about how people use websites. This helps website owners improve user experience and optimize their sites.
Disadvantages
Cons of cookies
Details
Privacy
Without their consent, cookies can be used to track and profile people - possibly breaching their privacy.
Security
If cookies are used to store sensitive data or if unauthorized individuals gain access to them, it can pose a security concern.
User control
The amount of data that cookies gather may make some users uncomfortable, and they may decide to block or delete cookies.
Compatibility
Cookies might not function effectively in every browser or on every device, which could result in inconsistent user experiences.
Use cases
Advertising: Cookies can track user behavior and interests and hence can be use to displaying relevant ads to end users. This can boost conversion rate and make it easier for advertisers to connect with their target audience.
E-commerce: Cookies can record data related to login, shipping, and even items in shopping carts. Developers can use these informations to improve user experience and make the checkout process smoother.
Analytics: Cookies can track different kinds of data on your website, like user behavior, location, device, reference site, and more. Website owners can use this data can help them improve user experience and make business decisions.
Security: Cookies can prevent fraud and unauthorized access. It can store login credentials and authenticate the user when trying to log in. Cookies can also identify multiple login attempts from different locations or devices.
Integration of social media: Cookies are used by social media platforms to track user behavior and preferences. It makes a note of language, time zone, location, likes, shares, and even comments, to deliver a personalized and optimised user experience.
Local storage vs session storage vs cookies
This table represents how local storage, session storage, and cookies stack against each other.
Aspect
Local storage
Session storage
Cookies
Storage capacity
Upto 10 MB per domain
5-10 MB per session
Up to 4 KB per cookie
Data accessibility
Can only be viewed by the domain that created them
Can only be accessed by the domain that created them
Can be accessed by any domain that has access to the cookie i.e server and client.
Data expiration
Kept until it is deleted by the user or the website that created it
Automatically deleted when a person quits their browser or leaves a website.
You can set expiration time for a cookie. It varies from few hours or days, while others may set them to last for months or even years.
Data security
More secure than cookies as it is not transferred to the server with every request
More secure than cookies as it is not transferred to the server with every request, but still susceptible to XSS attacks
Susceptible to interception by hackers
Browser support
Supported by most modern browsers like
Google Chrome (above version 4), Mozilla Firefox (above version 3.5), Apple Safari (above version 4), Microsoft Edge(above version 12)
Internet Explorer(above version 8), Opera (above version 10.5).
Supported by modern browsers like Google Chrome (above version 5), Mozilla Firefox (above version 2), Apple Safari (above version 4), Microsoft Edge (above version 12), Internet Explorer (above version 8), Opera (above version 10.60).
Accepted by most modern browsers like Google Chrome, Mozilla Firefox, Apple Safari,
Microsoft Edge, Internet Explorer, Opera.
Use Cases
Storing user preferences, caching data, and enabling offline functionality
Storing temporary data during a user session, such as data from a form or shopping cart
User authentication, tracking, and personalization
Conclusion
Building good online apps requires an understanding of the differences between local storage, session storage, and cookies. We know that cookies have been around for 1994, while local storage and session storage were introduced with HTML in 2008. Both local storage and session storage are more adaptable and have greater storage space, making them suitable for a wide range of use cases.
By selecting the appropriate storage method, you can enhance the performance and user experience of your web application. So next time you're building a web app, keep in mind the differences between local storage, session storage, and cookies to make the most of browser storage.
That’s all for now. Happy coding!
Call to Action Feel free to comment or write to us in case you have any further questions at support@zipy.ai. We would be happy to help you. In case you want to explore Zipy for your app, you can sign up here or book a demo here.
Call to Action Feel free to comment or write to us in case you have any further questions at support@zipy.ai. We would be happy to help you. In case you want to explore Zipy for your app, you can sign up here or book a demo here.
Call to Action Feel free to comment or write to us in case you have any further questions at support@zipy.ai. We would be happy to help you. In case you want to explore Zipy for your app, you can sign up here or book a demo here.
Call to Action Feel free to comment or write to us in case you have any further questions at support@zipy.ai. We would be happy to help you. In case you want to explore Zipy for your app, you can sign up here or book a demo here.
Call to Action Feel free to comment or write to us in case you have any further questions at support@zipy.ai. We would be happy to help you. In case you want to explore Zipy for your app, you can sign up here or book a demo here.
Call to Action
Feel free to comment or write to us in case you have any further questions at support@zipy.ai. We would be happy to help you. In case you want to explore for your app, you can sign up or book a demo.