What is local storage?
In web development, local storage is a type of storage that allows web applications to store data locally within the user’s browser. It is a persistent data storage mechanism that allows data to be saved across browser sessions, allowing web applications to maintain state even after the browser has been closed and reopened.
How to use local storage
To use local storage, you can set values using the
setItem() method and retrieve them using the
getItem() method. For example:
localStorage.setItem('key', 'value'); const value = localStorage.getItem('key');
You can also remove items from local storage using the
removeItem() method, or clear all items from local storage using the
Local storage is useful for storing data that needs to be persisted across browser sessions, such as user preferences or application state. It is important to note, however, that local storage is limited in size and may not be suitable for storing large amounts of data.
Keep in mind that local storage is shared between all Red Apps, hence keys should be unique as possible, e.g. prefixed with Red App name. For the same reason you should not use
clear() method from the Web API, instead remove keys one by one.
Local storage vs session storage
Local storage and session storage are both types of web storage that allow a website to store and retrieve data in the user’s browser. However, they have some differences:
Persistence: Local storage is persistent, meaning the data stored in local storage remains in the browser even after the browser is closed. In contrast, data stored in session storage is only available for the current window or tab, and is deleted when the window or tab is closed.
Scope: Local storage is available to all windows and tabs from the same origin (website), while session storage is only available to the current window or tab.
Size: Local storage has a larger maximum size than session storage, typically around 5MB. Session storage has a smaller maximum size, typically around 2MB.
In general, you can use local storage for data that you want to persist beyond the current session, such as user preferences, while session storage is more suitable for temporary data that only needs to be available during a single browsing session.
It is important to be aware that local storage is not a secure storage solution.
Additionally, local storage data is persisted even if the user closes the browser or clears their browsing history, so data can be compromised even after the user has left the web application.
For these reasons, it is generally not recommended to store sensitive or confidential information in local storage. If you need to store sensitive data (e.g. PCI/GDPR data) in a web application, you should consider using a more secure storage solution.