We explore on How to Choose between various client-side storage mechanisms and follow best practices to securely and effectively use these.
Blog
I Hope you like it and please provide your valuable feedback. I would try to cover various topics in full stack that would be important to you in your development journey as well as help you in interviews.
Client-side storage refers to the ability of a web browser to store data locally on a user's device. This data can be stored using various mechanisms such as cookies, localStorage, and sessionStorage, indexedDb.
Persistence: Client-side storage allows web applications to store data locally on the user's device, enabling the application to remember user preferences, settings, and other information across sessions.
Performance: Storing data on the client side reduces the need to repeatedly fetch data from the server, improving performance and reducing network traffic.
Offline Support: Client-side storage enables web applications to work offline by storing necessary data locally, allowing users to access content even when they are not connected to the internet.
Enhanced User Experience: By utilizing client-side storage, web applications can provide a more seamless and personalized user experience by customizing content based on stored data.
Overall, client-side storage is essential for enhancing performance, enabling offline capabilities, and improving user experience in web applications by storing data locally on the user's device.
Cookies: Cookies are small pieces of data stored by the browser and sent back to the server with each request. They are commonly used for session management, tracking user preferences, and storing small amounts of data. The storage capacity for Cookies is 4KB.
LocalStorage: LocalStorage allows web applications to store key-value pairs locally on the user's device. The data stored in localStorage persists even after the browser is closed and can be accessed across browser sessions. The storage capacity of local storage is typically limited to 5MB-10MB (Depends on browser) per origin, which is based on the combination of protocol, domain, and port. If you exceed this limit for a specific origin, the browser may start evicting older data to make space for new data.
SessionStorage: sessionStorage is similar to localStorage, but the data stored in sessionStorage is tied to a specific browsing session. Once the session ends (e.g., when the browser is closed), the data is cleared. The storage capacity for session Storage is 5MB.
IndexedDB: IndexedDB is a more advanced client-side storage mechanism that allows web applications to store large amounts of structured data locally. It provides a database-like storage solution with support for indexes and asynchronous operations.
Web Storage API: The Web Storage API encompasses both localStorage and sessionStorage and provides a simple way to store data on the client side.
Cache API: As the name suggests The Cache API allows web applications to store network requests and responses in a cache, enabling offline access and faster loading times for subsequent visits.
Each of these mechanisms has its own use cases and advantages, and the choice of storage mechanism depends on factors such as the type of data being stored, the required persistence, how data is going to be accessed and the amount of data to be stored.
LocalStorage is commonly used for storing small amounts of data that need to persist across browser sessions. It is suitable for scenarios where you need high persistence and have a moderate amount of data to store in key-value pairs.
Here are some scenarios and use cases where localStorage should be used:
User Preferences: Storing user preferences such as theme settings, language preferences, or layout customization.
Caching Data: Storing cached data to improve performance by reducing the need to fetch the same data repeatedly from the server.
Form Data: Saving form data temporarily to prevent data loss in case of accidental page refresh or navigation.
APIS for working with LocalStorage
localStorage.setItem("name", "vikram"); // set key-value pair
localStorage.getItem("name") // returns value stored associated with given key
localStorage.removeItem("name") // remove the localStorage item with given key
localStorage.clear() // removing all the localStorage items
// Note: Session Storage also profile setItem, getItem, removeItem and clear methods
Few Points to Note about LocalStorage
While localStorage can be convenient for non-sensitive data, it is important to avoid storing critical information in it due to security risks. Here are some reasons why critical information should not be stored in localStorage:
Security Concerns: Data stored in localStorage is accessible by JavaScript running on the same domain, making it vulnerable to cross-site scripting (XSS) attacks.
No Encryption: Data stored in localStorage is not encrypted, so sensitive information like passwords or personal details can be easily accessed if a malicious script gains access to it.
No Expiry Mechanism: Data stored in localStorage remains indefinitely unless explicitly cleared, posing a risk if sensitive information is stored and not properly managed.
Limited Storage: Each origin (protocol and domain) in the browser has a limited amount of storage available for local Storage, so storing large amounts of data can lead to performance issues or potential data loss.
In summary, while localStorage is suitable for non-sensitive data that requires persistence across browser sessions, it is crucial to avoid storing critical information in it to mitigate security risks and ensure data confidentiality.
Remember 🧐: Data stored in session Storage is only available for the duration of the page session. Once the browser tab or window is closed, the data is cleared.
Use cases Examples!
Form Data: Storing form data temporarily while a user navigates through multiple pages or steps of a form. This helps prevent data loss if the user accidentally refreshes the page.
Session-specific Information: Storing session-specific information such as temporary preferences or settings that are only relevant during the current browsing session.
Single Page Applications (SPAs): Managing state and data within a single page application where data needs to persist across different components or views within the same session.
Caching: Storing temporary data for caching purposes to improve performance within a specific browsing session without the need for long-term persistence.
Authentication Tokens: Storing temporary authentication tokens or session identifiers that are only valid for the current session to authenticate requests and manage user sessions.
Shopping Cart: Maintaining the contents of a shopping cart or temporary selections made by a user during a browsing session on an e-commerce website.
Game State: Saving game state or progress within a browser-based game to resume gameplay without losing progress during the same session.
In these scenarios, sessionStorage provides a convenient way to store temporary data that is only needed for the current session and does not need to persist across browser sessions. It helps maintain state within a specific browsing session without the need for explicit clearing or management, as the data is automatically cleared when the session ends.
Stateless Nature of HTTP: Each request made to a server is treated as independent and unique, regardless of whether it comes from the same user or not. The server doesn't retain any information about previous requests, so it doesn't store individual user information between requests. This approach is efficient for handling a large number of requests and reduces the need for storing unnecessary data on the server.
These leads us to use of cookies, which is sent and stored on your local machine to uniquely identify you. Cookies are automatically included in the HTTP request headers by the browser for the domain that the request is being made to, allowing the server to access and utilize the stored cookie data. The server can then use this information for various purposes such as authentication, session management, tracking user preferences, etc.
Note: LocalStorage and sessionStorage are not accessible to the server, unlike cookies, which are sent to the server with each request and can be read and modified by the server.
Cookies also supports expiry which is quite helpful in ensuring security, privacy and following various compilances.
Benefits of expiring nature of Cookies.
Use case Scenarios!
When storing critical information in cookies, it's important to follow security best practices to protect the data from unauthorized access or tampering. Here are some key practices:
By following these security practices, you can help protect critical information stored in cookies from unauthorized access and maintain the integrity of your application.
Copyright ©2024 Preplaced.in
Preplaced Education Private Limited
Ibblur Village, Bangalore - 560103
GSTIN- 29AAKCP9555E1ZV