IndexedDB should be used when it is necessary to store a large amount of structured data, support offline functions, conduct efficient queries or process binary files, including: 1. Store a large amount of structured data (such as documents, cached API responses); 2. Implement PWA or offline functions; 3. Efficiently query data through indexes (such as search by date, classification); 4. Process binary data such as pictures and audio (using Blobs). When only a small number of simple key-value pairs (such as user preferences, tokens), no complex queries or transactions, and the simplicity of implementation is pursued, localStorage or sessionStorage should be continued. IndexedDB is the most powerful client storage solution in the browser, suitable for complex applications, while localStorage is suitable for lightweight scenarios. The two are positioned differently and the choice should be based on actual needs. The final conclusion is: When strong storage capabilities are required, IndexedDB is irreplaceable, otherwise simple solutions will be preferred.
When building modern web applications, handling data efficiently on the client side is cruel — especially for offline functionality, performance, and smoother user experiences. While localStorage
is simple and widely used, it falls short when dealing with large or structured data. That's where IndexedDB comes in.

IndexedDB is a low-level, asynchronous API for storing significant amounts of structured data in the browser, including files and blobs. It supports full-text search and complex queries via indexes. If you're building a PWA, offline-capable app, or just need robust client-side persistence, IndexedDB is the right tool — once you get past its step learning curve.
Here's a practical guide to help you use IndexedDB effectively.

? When to Use IndexedDB (and When Not To)
Use IndexedDB when:
- You need to store large amounts of structured data (eg, user documents, cached API responses, media metadata).
- You want offline support (eg, in PWAs).
- You need to query data efficiently using indexes (eg, search by date, category, etc.).
- Your app handles binary data like images or audio (via Blobs).
Stick with localStorage
or sessionStorage
when:

- You're storing small, simple key-value pairs (eg, user preferences, tokens).
- You don't need querying or transactions.
- Simplicity and quick implementation matter more than scalability.
? Think of
localStorage
as a notepad. IndexedDB is a full-fledged database.
? Core Concepts of IndexedDB
Before writing code, understand these key concepts:
- Database : A container for data (one per app or feature).
- Object Store : Like a table in SQL — holds records (objects).
- Key : A unique identifier for each record (can be auto-incremented).
- Transaction : All operations happen within a transaction (ensures consistency).
- Index : Allows querying object stores by properties other than the key.
- Cursor : Used to iterate over records efficiently.
IndexedDB is asynchronous and event-driven (though modern wrappers use Promises). You can't just “get” data synchronously — you request it and respond to success or error events.
?? Basic Setup and Usage (With Promises)
IndexedDB's native API uses callbacks, but wrapping it in Promises makes it much easier to work with. Here's a clean, minimal example:
// Open or create a database function openDB() { return new Promise((resolve, reject) => { const request = indexedDB.open('MyAppDB', 1); // Handle database upgrade (first time or version change) request.onupgradeneeded = (event) => { const db = event.target.result; // Create an object store for "products" if (!db.objectStoreNames.contains('products')) { const store = db.createObjectStore('products', { keyPath: 'id', autoIncrement: true }); // Create an index to search by category store.createIndex('category', 'category', { unique: false }); } }; request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); }
Now, let's add, read, and query data.
Add Data
async function addProduct(product) { const db = await openDB(); const tx = db.transaction('products', 'readwrite'); const store = tx.objectStore('products'); store.add(product); return tx.done; }
Get All Products
async function getAllProducts() { const db = await openDB(); const tx = db.transaction('products', 'readonly'); const store = tx.objectStore('products'); return new Promise((resolve, reject) => { const request = store.getAll(); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); }
Query by Index (eg, by Category)
async function getProductsByCategory(category) { const db = await openDB(); const tx = db.transaction('products', 'readonly'); const store = tx.objectStore('products'); const index = store.index('category'); return new Promise((resolve, reject) => { const request = index.getAll(category); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); }
? Remember: Every read/write happens in a transaction, and you must wait for it to complete (
tx.done
) if you want to catch errors properly.
? Tips for Real-World Use
Wrap IndexedDB in a Service or Utility
- Don't scatter
indexedDB.open()
calls everywhere. Create a simple wrapper class or module for consistent access.
- Don't scatter
Handle Version Upgrades Carefully
- Changing the schema requires incrementing the version number. Use
onupgradeneeded
to add/remove object stores or indexes.
- Changing the schema requires incrementing the version number. Use
Use Indexes for Performance
- If you frequently query by a field (eg,
status
,createdAt
), create an index for it.
- If you frequently query by a field (eg,
Watch for Quota Limits
- Browsers limit storage (usually 50%–80% of disk). Listen for
quotaerror
and handle gracefully.
- Browsers limit storage (usually 50%–80% of disk). Listen for
Clean Up Old Data
- Especially in long-running apps, periodically clear outdated or unused records.
Use
cursor
for Large Datasets- Instead of
getAll()
, use cursors to process records one at a time and avoid memory issues.
- Instead of
const request = store.openCursor(); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { console.log('Item:', cursor.value); cursor.continue(); // Move to next } };
? Alternatives and Wrappers
Because raw IndexedDB is verbose, consider these tools:
- Dexie.js – A popular, lightweight wrapper that simplifies queries and uses Promises/async-await.
const db = new Dexie('MyAppDB'); db.version(1).stores({ products: ' id, category' }); await db.products.add({ name: 'Phone', category: 'electronics' });
- idb – A tiny (1.5KB) Promised-based library by Jake Archibald.
- LocalForage – Offers a
localStorage
-like API but uses IndexedDB under the hood.
These make IndexedDB much more approachable without sacrificing power.
? Final Thoughts
IndexedDB is powerful but complex. For simple needs, localStorage
is fine. But when you need to store structured, searchable, or large data on the client, IndexedDB is the best option.
Start small: open a DB, create one object store, and perform basic CRUD operations. Use a wrapper like Dexie if you want faster progress. And always test storage behavior across browsers — especially around limits and user permissions.
Basically, IndexedDB isn't something you use every day, but when you need it, nothing else in the browser comes close.
The above is the detailed content of A Practical Guide to IndexedDB and Client-Side Storage. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ARIAattributesenhancewebaccessibilityforuserswithdisabilitiesbyprovidingadditionalsemanticinformationtoassistivetechnologies.TheyareneededbecausemodernJavaScript-heavycomponentsoftenlackthebuilt-inaccessibilityfeaturesofnativeHTMLelements,andARIAfill

React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementation; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.

Let’s talk about the key points directly: Merging resources, reducing dependencies, and utilizing caches are the core methods to reduce HTTP requests. 1. Merge CSS and JavaScript files, merge files in the production environment through building tools, and retain the development modular structure; 2. Use picture Sprite or inline Base64 pictures to reduce the number of image requests, which is suitable for static small icons; 3. Set browser caching strategy, and accelerate resource loading with CDN to speed up resource loading, improve access speed and disperse server pressure; 4. Delay loading non-critical resources, such as using loading="lazy" or asynchronous loading scripts, reduce initial requests, and be careful not to affect user experience. These methods can significantly optimize web page loading performance, especially on mobile or poor network

Shallowrenderingtestsacomponentinisolation,withoutchildren,whilefullrenderingincludesallchildcomponents.Shallowrenderingisgoodfortestingacomponent’sownlogicandmarkup,offeringfasterexecutionandisolationfromchildbehavior,butlacksfulllifecycleandDOMinte

StrictMode does not render any visual content in React, but it is very useful during development. Its main function is to help developers identify potential problems, especially those that may cause bugs or unexpected behavior in complex applications. Specifically, it flags unsafe lifecycle methods, recognizes side effects in render functions, and warns about the use of old string refAPI. In addition, it can expose these side effects by intentionally repeating calls to certain functions, thereby prompting developers to move related operations to appropriate locations, such as the useEffect hook. At the same time, it encourages the use of newer ref methods such as useRef or callback ref instead of string ref. To use Stri effectively

Create TypeScript-enabled projects using VueCLI or Vite, which can be quickly initialized through interactive selection features or using templates. Use tags in components to implement type inference with defineComponent, and it is recommended to explicitly declare props and emits types, and use interface or type to define complex structures. It is recommended to explicitly label types when using ref and reactive in setup functions to improve code maintainability and collaboration efficiency.

There are three key points to be mastered when processing Vue forms: 1. Use v-model to achieve two-way binding and synchronize form data; 2. Implement verification logic to ensure input compliance; 3. Control the submission behavior and process requests and status feedback. In Vue, form elements such as input boxes, check boxes, etc. can be bound to data attributes through v-model, such as automatically synchronizing user input; for multiple selection scenarios of check boxes, the binding field should be initialized into an array to correctly store multiple selected values. Form verification can be implemented through custom functions or third-party libraries. Common practices include checking whether the field is empty, using a regular verification format, and displaying prompt information when errors are wrong; for example, writing a validateForm method to return the error message object of each field. You should use it when submitting

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS
