Home > Technology peripherals > It Industry > 10 Client-side Storage Options and When to Use Them

10 Client-side Storage Options and When to Use Them

Christopher Nolan
Release: 2025-02-10 14:22:12
Original
874 people have browsed it

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:

  • Keep the status of the client application—such as the current screen, input data, user preferences, etc.
  • Utilities that access local data or files with strict privacy requirements.
  • Progressive Web Application (PWA) that works offline.

The following are ten browser data storage options:

  1. JavaScript variables
  2. DOM node storage
  3. Web storage (localStorage and sessionStorage)
  4. IndexedDB
  5. Cache API (do not use AppCache!)
  6. File System Access API
  7. File and Directory Entry API
  8. cookie
  9. window.name
  10. WebSQL

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...

Key Points

  • JavaScript variable: Temporary data is the fastest, but it will be cleared when the page is refreshed; it is best for data that does not need to be persisted to save more than the current page viewed.
  • DOM node storage: Similar to JavaScript variables in terms of speed and persistence, but allows state storage in HTML elements; for component-specific state.
  • Web storage (localStorage and sessionStorage): Suitable for persistent storage of small amounts of data (localStorage) or session storage (sessionStorage); due to synchronization operations, it is not suitable for large data sets.
  • IndexedDB: Best for large amounts of structured data that need to be persisted; supports transactions and indexes, but the API is complex.
  • Cached API: Ideally used to store network responses in PWA for offline use; modern APIs, but limited to network data, are not suitable for general state storage.
  • cookie: useful for small data that must be sent with HTTP requests; has good persistence, but limited capacity and may have security issues.

Data persistence

Usually, the data you store will be:

  1. Permanence: It will remain until your code chooses to delete it, or
  2. Volatility: It remains until the browser session ends, usually when the user closes the tab.

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.

  1. JavaScript variables

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...

const
  a = 1,
  b = 'two',
  state = {
    msg:  'Hello',
    name: 'Craig'
  };
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Pros:

  • Easy to use
  • Quick
  • No need for serialization or deserialization

Disadvantages:

  • Fragile: Refreshing or closing the tab will clear everything
  • Third-party scripts can check or override global (window) values

You are already using variables. You can consider permanent storage of variable state when page uninstallation.

  1. DOM node storage

IndicatorInstructionsCapacity 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-:

  1. Attributes will never have associated HTML functionality
  2. You can access the values ​​through the dataset attribute instead of the longer .setAttribute() and .getAttribute() methods.

values ​​are stored as strings, so serialization and deserialization may be required. For example:

// 定位<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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Pros:

  • You can define values ​​in JavaScript or HTML - for example
  • Helps store the state of a specific component
  • DOM is fast! (Contrary to popular opinions)

Disadvantages:

  • Fragile: Refreshing or closing the tab will clear everything (unless the value is rendered into HTML by the server)
  • Strings only: Serialization and deserialization are required
  • Biger DOM will affect performance
  • Third-party scripts can check or overwrite values

DOM nodes store slower than variables. Use it with caution when it is useful to store the state of a component in HTML.

  1. Web storage (localStorage and sessionStorage)

IndicatorInstructionsCapacity 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:

  1. window.localStorage stores persistent data, and
  2. window.sessionStorage retains session-only data while the browser tab remains open (but see data persistence)

Storage or update named items using .setItem():

localStorage.setItem('value1', 123);
localStorage.setItem('value2', 'abc');
localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Retrieve them using .getItem():

const state = JSON.parse( localStorage.getItem('state') );
Copy after login
Copy after login
Copy after login
Copy after login

Delete them with .removeItem():

localStorage.removeItem('state')
Copy after login
Copy after login
Copy after login

Other properties and methods include:

  • .length: Number of stored items
  • .key(N): Name of the Nth key
  • .clear(): Delete all stored items

Changing any value will raise a storage event in other browser tabs/windows connected to the same domain. Your application can respond accordingly:

const
  a = 1,
  b = 'two',
  state = {
    msg:  'Hello',
    name: 'Craig'
  };
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Pros:

  • Simple Name/Value Pair API
  • Session and persistent storage options
  • Good browser support

Disadvantages:

  • Strings only: Serialization and deserialization are required
  • Unstructured data without transactions, indexes or searches
  • Synchronous access affects the performance of large datasets

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.

  1. IndexedDB

IndicatorsInstructionsCapacity 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):

// 定位<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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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:

localStorage.setItem('value1', 123);
localStorage.setItem('value2', 'abc');
localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Once the db connection is ready, you can add new data items in a transaction:

const state = JSON.parse( localStorage.getItem('state') );
Copy after login
Copy after login
Copy after login
Copy after login

You can retrieve values, such as the first item:

localStorage.removeItem('state')
Copy after login
Copy after login
Copy after login

Pros:

  • Flexible data storage with maximum space
  • Strong transactions, indexes and search options
  • Good browser support

Disadvantages:

  • A complex callback and event-based API

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.

  1. Cache API

IndicatorInstructionsCapacity 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:

const
  a = 1,
  b = 'two',
  state = {
    msg:  'Hello',
    name: 'Craig'
  };
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Similar functions can retrieve items from cache. In this example, it returns the response body text:

// 定位<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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Pros:

  • Storage any network response
  • Can improve the performance of web applications
  • Allow web applications to run offline
  • Modern Promise-based API

Disadvantages:

  • Not suitable for storing application status
  • Maybe less useful outside of progressive web applications
  • Apple is not friendly to PWA and cache APIs

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

AppCache is the predecessor of the cache API that has expired. This is not the storage solution you are looking for. There is nothing good to watch here. Please leave.

    File System Access API

MetricsInstructionsCapacity 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:
localStorage.setItem('value1', 123);
localStorage.setItem('value2', 'abc');
localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Web applications can safely read and write to local file systems
  • Reduces the need to upload files or process data on the server
  • A great feature of progressive web applications
  • Disadvantages:

The browser supports minimal (Chrome only)
  • API may change
  • This storage option is most exciting to me, but you will have to wait a few more years before you can use it for production.

    File and Directory Entry API

MetricsInstructionsCapacity 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
  • Disadvantages:

Non-standard, incompatibility between implementations, and behavior may change.
  • MDN clearly states:

Do not use this feature on production websites. It will take at least a few years for broad support.

  1. cookie

IndicatorInstructionsCapacity 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.

document.cookie sets the cookie value in client JavaScript. You must define a string where the name and value are separated by an equal sign (=). For example:

const
  a = 1,
  b = 'two',
  state = {
    msg:  'Hello',
    name: 'Craig'
  };
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Values ​​cannot contain commas, semicolons, or spaces, so encodeURIComponent() may be required:

// 定位<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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
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.
  • ;path=: If not set, the cookie is only available in the current path and its subpaths. Set ;path=/ to allow any path in the domain.
  • ;max-age=: cookie expiration time (seconds)—for example;max-age=60.
  • ;expires=: cookie expiration date—for example;expires=Thu, 04 July 2021 10:34:38 ​​UTC (use date.toUTCString() for appropriate formatting).
  • ;secure: The cookie will be transmitted over HTTPS only.
  • ;HTTPOnly: Makes cookies unable to access client JavaScript.
  • ;samesite=: Controls whether another domain can access cookies. Set it to lax (default, share cookies to the current domain), strict (blocks the initial cookie when following the link from another domain) or none (unlimited).
Example: Set a status cookie that expires after 10 minutes and can be used in any path to the current domain:

localStorage.setItem('value1', 123);
localStorage.setItem('value2', 'abc');
localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
document.cookie returns a string containing each name and value pair, separated by a semicolon. For example:

const state = JSON.parse( localStorage.getItem('state') );
Copy after login
Copy after login
Copy after login
Copy after login
The function below parses the string and converts it into an object containing a name-value pair. For example:

localStorage.removeItem('state')
Copy after login
Copy after login
Copy after login
Pros:

    Reliable way to preserve state between client and server
  • Domain and (optional) paths only
  • Use max-age (seconds) or Expires (date) for automatic expiration control
  • Used by default in the current session (set the expiration date to persist data beyond page refresh and tab close)
Disadvantages:

  • Cookies are often blocked by browsers and plugins (they are usually converted to session cookies so that the website can continue to work)
  • Clumsy JavaScript implementation (it's better to create your own cookie handler or choose a library like js-cookie)
  • Strings only (requires serialization and deserialization)
  • Storage space is limited
  • Cookies can be checked by third-party scripts unless you restrict access
  • Accused of privacy violations (regional legislation may require you to show warnings about non-essential cookies)
  • Cookie data is attached to each HTTP request and response, which may affect performance (storing 50Kb of cookie data and then requesting ten 1-byte files will generate a million bytes of bandwidth)

Avoid using cookies unless there is no viable alternative.

  1. window.name

MetricsInstructionsCapacity 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:

const
  a = 1,
  b = 'two',
  state = {
    msg:  'Hello',
    name: 'Craig'
  };
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Check the value using the following method:

// 定位<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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Pros:

  • Easy to use
  • Data available for session-only

Disadvantages:

  • Strings only: Serialization and deserialization are required
  • Pages in other fields can read, modify or delete data (don't use it for sensitive information)

window.name was never designed for data storage. This is a trick, and there are better options for .

  1. WebSQL

IndicatorInstructionsCapacity 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:

localStorage.setItem('value1', 123);
localStorage.setItem('value2', 'abc');
localStorage.setItem('state', JSON.stringify({ a:1, b:2, c:3 }));
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Chrome and some versions of Safari support this technology, but Mozilla and Microsoft oppose it and instead support IndexedDB.

Pros:

    Designed for powerful client data storage and access
  • Familiar SQL syntax often used by server-side developers
Disadvantages:

    Browser support is limited and there are errors
  • Inconsistency between SQL syntax between browsers
  • Async but clumsy callback-based API
  • Poor performance
Don't use WebSQL! It has been not a viable option since the 2010 specification was deprecated.

Check the storage

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:

const state = JSON.parse( localStorage.getItem('state') );
Copy after login
Copy after login
Copy after login
Copy after login
There are two other asynchronous methods available:

  • .persist(): Return true if the site has permission to store persistent data,
  • .persisted(): Returns true if the site has stored persistent data.

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.

Storage Hotpot

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!

Frequently Asked Questions about Local Storage Alternatives

What can I use instead of local storage?

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).

When shouldn't you use local storage?

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.

Which is better, localStorage or sessionStorage?

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.

What is a client database?

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.

What are the different types of client storage?

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.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template