Home >Technology peripherals >It Industry >10 Client-side Storage Options and When to Use Them
Browser data storage and operations, also known as client storage, are useful when data is not needed or cannot be sent to a web server.
Scenarios for browser data storage and operation include:
The following are ten browser data storage options:
This article will explore these ten different ways of storing browser data, covering their limitations, pros and cons, and the best uses of each technology.
Before browsing these options, take a quick look at data persistence...
Usually, the data you store will be:
The actual situation is more detailed.
Permanent data may be blocked or deleted by users, operating systems, browsers, or plug-ins at any time. When the browser approaches the capacity allocated to that storage type, it may decide to delete older or larger items.
The browser will also record the page status. You can leave from the website navigation and click Back or Close and reopen the tab; the page should look the same. Variables and data that are considered session-only are still available.
Metrics
Instructions
The capacity is not strictly limited, but when you fill in memory, the browser may slow down or crash the read/write speeds are the most Fast options have poor persistence: Data will be refreshed by the browser and cleared to store state in JavaScript variables is the fastest and easiest option. I believe you don't need an example, but...
<code class="language-javascript">const a = 1, b = 'two', state = { msg: 'Hello', name: 'Craig' };</code>
Pros:
Disadvantages:
You are already using variables. You can consider permanent storage of variable state when page uninstallation.
Indicator
Instructions
Capacity is not strictly limited, but is not suitable for large amounts of data to read/write fast, poor persistence: data may be refreshed by other scripts or refreshed Clearing most DOM elements (on page or in memory) can store values in named properties. It is safer to use attribute names prefixed with data-:
values are stored as strings, so serialization and deserialization may be required. For example:
<code class="language-javascript">// 定位<main>元素 </main>const main = document.querySelector('main'); // 存储值 main.dataset.value1 = 1; main.dataset.state = JSON.stringify({ a:1, b:2 }); // 检索值 console.log( main.dataset.value1 ); // "1" console.log( JSON.parse(main.dataset.state).a ); // 1</code>
Pros:
Disadvantages:
DOM nodes store slower than variables. Use it with caution when it is useful to store the state of a component in HTML.
Indicator
Instructions
Capacity 5MB Read/Write Speed Synchronous Operation: May be slow Persistent data remains until it is cleared Web storage Provides two similar APIs to define name/value pairs. Use:
Storage or update named items using .setItem():
<code class="language-javascript">localStorage.setItem('value1', 123); localStorage.setItem('value2', 'abc'); localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));</code>
Retrieve them using .getItem():
<code class="language-javascript">const state = JSON.parse( localStorage.getItem('state') );</code>
Delete them with .removeItem():
<code class="language-javascript">localStorage.removeItem('state')</code>
Other properties and methods include:
Changing any value will raise a storage event in other browser tabs/windows connected to the same domain. Your application can respond accordingly:
<code class="language-javascript">const a = 1, b = 'two', state = { msg: 'Hello', name: 'Craig' };</code>
Pros:
Disadvantages:
Web storage is perfect for simpler, smaller, temporary values. It's not very suitable for storing large amounts of structured information, but you can avoid performance issues by writing data when the page is unloaded.
Indicators
Instructions
Capacity depends on the equipment. At least 1GB, but up to 60% of the remaining disk space read/write speed Fast persistence data remains until it is cleared IndexedDB provides a low-level API similar to NoSQL for storing large amounts of data. The store can be indexed, can be updated using transactions, and can be searched using asynchronous methods.
IndexedDB API is complex and requires some event processing. The following function opens a database connection when passing the name, version number, and optional upgrade function (called when the version number changes):
<code class="language-javascript">// 定位<main>元素 </main>const main = document.querySelector('main'); // 存储值 main.dataset.value1 = 1; main.dataset.state = JSON.stringify({ a:1, b:2 }); // 检索值 console.log( main.dataset.value1 ); // "1" console.log( JSON.parse(main.dataset.state).a ); // 1</code>
The following code connects to myDB database and initializes the todo object store (similar to SQL tables or MongoDB collections). It then defines an auto-increment key named id:
<code class="language-javascript">localStorage.setItem('value1', 123); localStorage.setItem('value2', 'abc'); localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));</code>
Once the db connection is ready, you can add new data items in a transaction:
<code class="language-javascript">const state = JSON.parse( localStorage.getItem('state') );</code>
You can retrieve values, such as the first item:
<code class="language-javascript">localStorage.removeItem('state')</code>
Pros:
Disadvantages:
IndexedDB is the best choice for reliable storage of large amounts of data, but you need to use a wrapper library such as idb, Dexie.js, or JsStore.
Indicator
Instructions
Capacity depends on the device, but Safari limits each domain to 50MB of read/write speed fast persistent data to be Clear or cache API provides storage for HTTP request and response object pairs until two weeks later in Safari. You can create as many named caches as many as you want to store any number of network data items.
This API is commonly used in service workers to cache network responses for progressive web applications. When the device is disconnected from the network, the cached assets can be reprovided so that the web application can run offline.
The following code stores the network response in a cache called myCache:
<code class="language-javascript">const a = 1, b = 'two', state = { msg: 'Hello', name: 'Craig' };</code>
Similar functions can retrieve items from cache. In this example, it returns the response body text:
<code class="language-javascript">// 定位<main>元素 </main>const main = document.querySelector('main'); // 存储值 main.dataset.value1 = 1; main.dataset.state = JSON.stringify({ a:1, b:2 }); // 检索值 console.log( main.dataset.value1 ); // "1" console.log( JSON.parse(main.dataset.state).a ); // 1</code>
Pros:
Disadvantages:
The cache API is the best choice for storing files and data retrieved from the network. You might use it to store application state, but it is not designed for this purpose and there are better options. 5.5 AppCache
Metrics
Instructions
Capacity depends on the remaining disk space read/write speed depends on file system persistence data remains until cleared file system access The API allows the browser to read, write, modify and delete files in the local file system. The browser runs in a sandbox environment, so the user must grant permissions to a specific file or directory. This will return a FileSystemHandle so that the web application can read or write data like a desktop application.
The following function saves the blob to a local file:
Pros:
<code class="language-javascript">localStorage.setItem('value1', 123); localStorage.setItem('value2', 'abc'); localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));</code>
Web applications can safely read and write to local file systems
The browser supports minimal (Chrome only)
Metrics
Instructions
Capacity depends on the remaining disk space Read/write speed Unknown Persistence data remains until it is cleared File and Directory Entry API provides A sandbox file system that can be used for domains that create, write, read, and delete directories and files.
Pros:
There may be some interesting uses
Non-standard, incompatibility between implementations, and behavior may change.
Do not use this feature on production websites
Avoid using cookies unless there is no viable alternative.
Check the value using the following method: Pros: Disadvantages: window.name was never designed for data storage. This is a trick, and there are better options for .
Indicator
The application panel in the browser developer tool (called Storage in Firefox) allows you to view, modify and clear localStorage, sessionStorage, IndexedDB, WebSQL, cookies, and cache storage. You can also check cookie data sent in HTTP request and response headers by clicking on any item in the Web panel of the developer tool. These storage solutions are not perfect, you need to adopt multiple solutions in complex web applications. This means learning more APIs. But it’s a good thing to have a choice in every situation – of course, let’s say you can choose the right option! When looking for alternatives to local storage in web development, options such as session storage, cookies, and IndexedDB can be considered. Session storage provides temporary storage for page sessions, while cookies are small pieces of data sent with each HTTP request that can be used for session management and storing limited data. IndexedDB provides a more powerful solution for storing structured data on the client side, making it suitable for applications that require asynchronous data retrieval.
Server-side storage solutions (such as MySQL, PostgreSQL, MongoDB) or cloud-based databases (such as Firebase, AWS DynamoDB, or Google Cloud Firestore) may be preferable for broader data storage or when security and persistence are critical. . Additionally, some client frameworks provide their own state management solutions, while service workers can cache data and assets for offline functionality, making them suitable for progressive web applications (PWAs). Local storage is a universal client storage solution, but in some cases it may not be the most suitable option. First, local storage is not suitable for storing sensitive or confidential information because it lacks encryption or security measures that make it vulnerable to unauthorized access. Critical data such as passwords or personal identities should be stored securely on the server side using a strong security protocol.
Second, local storage has limited capacity, usually around 5-10 MB per domain. It is not suitable for applications that need to process large amounts of data. In this case, server-side databases or more powerful client options such as IndexedDB should be considered to accommodate larger data sets.
Finally, local storage can cause performance issues, especially when dealing with large datasets, as it runs synchronously and can block the main thread. For performance-critical applications, you can use asynchronous storage solutions such as IndexedDB or implement memory caching to maintain a smooth user experience.
In summary, while local storage is valuable for lightweight, non-sensitive data storage, the specific requirements of the project must be evaluated. For sensitive information, large data sets, or performance-critical applications, alternative storage solutions should be explored to ensure data security, scalability, and the best user experience. The choice of localStorage and sessionStorage mainly depends on the data persistence duration you need and your specific use case.
localStorage is a better choice when you need data to be persisted between browser sessions. It is suitable for storing data such as user preferences, settings, or cache resources, which should be retained to the user even if the user closes the browser and returns to the website later. Its persistence and greater storage capacity make it ideal for scenarios where long-term data retention is required.
SessionStorage, on the other hand, is ideal for data that is only available during the current page session. When a user closes a tab or browser, the data is automatically cleared, ensuring privacy and reducing the risk of unintentional storage of unnecessary information. This makes it ideal for managing temporary data such as form data, cart content, or state management in a single user interaction. Client database, also known as front-end database, is a database that resides in the web application client (usually in the user's web browser) and runs there. It is used to store and manage data on client devices, allows web applications to work offline, reduce server load, and improve user experience by minimizing the need for frequent server requests. Client databases are often used in web development to store and retrieve data directly on the user's device.
One of the most common examples of client databases is IndexedDB, a low-level JavaScript API that provides a structured database for storing large amounts of data in a web browser. IndexedDB allows developers to create, read, update, and delete data, making it suitable for applications that require offline storage and management of large amounts of information.
Other examples of client databases include web storage (localStorage and sessionStorage) for storing small amounts of data, as well as various in-memory databases implemented in JavaScript for temporary data storage during user sessions.
Client databases are particularly useful for web applications such as progressive web applications (PWAs), where functionality is required to be maintained even if the user is offline or has limited internet connection. They complement the server-side database by providing a mechanism to store data locally on user devices, thereby reducing latency and enhancing the user experience. There are many forms of client storage in web development, each with its own characteristics and use cases.
A common type is web storage, which includes localStorage and sessionStorage. localStorage is suitable for storing small amounts of data that needs to be persisted across browser sessions, making it suitable for user preferences or settings. Instead, sessionStorage is session-limited, storing data only during a single page session, making it ideal for temporary data, such as shopping cart content or form data required during user interaction with web pages.
Another option is IndexedDB, a more advanced client database system. IndexedDB provides structured storage for managing large amounts of data on users' devices. It supports asynchronous data retrieval, indexing, transactions, and more, making it ideal for applications that require complex data processing and offline capabilities such as progressive web applications (PWA).
Additionally, cookies are small data fragments that can be stored on the client device and sent to the server with each HTTP request. Although not often used in general data storage today, cookies can still be used for tasks such as session management, user authentication, and tracking user preferences.
Each type of client storage has its pros and cons, and the choice depends on your specific requirements such as data size, persistence requirements, and use cases. . It will take at least a few years for broad support.
cookie
Indicator
Instructions
Capacity 80Kb per domain (20 cookies, up to 4Kb per cookie) fast read/write speed and good durability: Data is kept until it is cleared or expired cookies are domain-specific data. They are known for tracking people’s reputations, but they are essential for any system that needs to maintain server status, such as login. Unlike other storage mechanisms, cookies are usually passed between the browser and the server in each HTTP request and response. Both devices can check, modify and delete cookie data.
<code class="language-javascript">const
a = 1,
b = 'two',
state = {
msg: 'Hello',
name: 'Craig'
};</code>
Values cannot contain commas, semicolons, or spaces, so encodeURIComponent() may be required: <code class="language-javascript">// 定位<main>元素
</main>const main = document.querySelector('main');
// 存储值
main.dataset.value1 = 1;
main.dataset.state = JSON.stringify({ a:1, b:2 });
// 检索值
console.log( main.dataset.value1 ); // "1"
console.log( JSON.parse(main.dataset.state).a ); // 1</code>
Other cookie settings can be attached using semicolon delimiters, including: ;domain=: If not set, the cookie is only available in the current URL domain. Use ;path=mysite.com allows it to be used on any subdomain of mysite.com.
Example: Set a status cookie that expires after 10 minutes and can be used in any path to the current domain: <code class="language-javascript">localStorage.setItem('value1', 123);
localStorage.setItem('value2', 'abc');
localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));</code>
document.cookie returns a string containing each name and value pair, separated by a semicolon. For example: <code class="language-javascript">const state = JSON.parse( localStorage.getItem('state') );</code>
The function below parses the string and converts it into an object containing a name-value pair. For example: <code class="language-javascript">localStorage.removeItem('state')</code>
Pros: Reliable way to preserve state between client and server
Disadvantages:
window.name
Metrics
Instructions
Capacity changes, but should be able to accommodate several megabytes of read/write speeds Fast persistence session data remains to tab close Until the window.name property sets and gets the name of the window browsing context. You can set a single string value that persists between refreshing the browser or linking to another location and clicking back. For example: <code class="language-javascript">const
a = 1,
b = 'two',
state = {
msg: 'Hello',
name: 'Craig'
};</code>
<code class="language-javascript">// 定位<main>元素
</main>const main = document.querySelector('main');
// 存储值
main.dataset.value1 = 1;
main.dataset.state = JSON.stringify({ a:1, b:2 });
// 检索值
console.log( main.dataset.value1 ); // "1"
console.log( JSON.parse(main.dataset.state).a ); // 1</code>
Instructions Capacity 5MB per domain read/write slow persistence data until it is cleared WebSQL is a SQL-like database Storage attempts to introduce browsers. Sample code:
<code class="language-javascript">localStorage.setItem('value1', 123);
localStorage.setItem('value2', 'abc');
localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));</code>
Chrome and some versions of Safari support this technology, but Mozilla and Microsoft oppose it and instead support IndexedDB. Designed for powerful client data storage and access
Disadvantages: Browser support is limited and there are errors
Don't use WebSQL! It has been not a viable option since the 2010 specification was deprecated.
Storage API can check the available space of Web storage, IndexedDB, and cache APIs. All browsers except Safari and IE support a Promise-based API, which provides a .estimate() method to calculate quotas (the space available to the domain) and usage (the space used). For example: <code class="language-javascript">const state = JSON.parse( localStorage.getItem('state') );</code>
There are two other asynchronous methods available:
Storage Hotpot
Frequently Asked Questions about Local Storage Alternatives
What can I use instead of local storage?
When shouldn't you use local storage?
Which is better, localStorage or sessionStorage?
What is a client database?
What are the different types of client storage?
The above is the detailed content of 10 Client-side Storage Options and When to Use Them. For more information, please follow other related articles on the PHP Chinese website!