Progressive Web Apps (PWAs) provide app-like experiences through modern web technologies. One important capability of a PWA is storing data locally so users can access information without constantly communicating with a server.
IndexedDB is a browser-based database that allows web applications to store structured data, including objects, records, and larger datasets. It is particularly useful for PWAs that need offline access, local data management, faster interactions, and synchronization with remote servers.
Businesses can use IndexedDB in inventory applications, e-commerce platforms, task management systems, field service applications, educational platforms, and other data-driven PWAs.
In this guide, we will explore how to build a PWA with IndexedDB, design its local storage architecture, implement CRUD operations, support offline functionality, and synchronize local data with a backend server.
1. What Is IndexedDB?
IndexedDB is a built-in browser database designed to store structured data on a user’s device.
Unlike localStorage, which primarily stores small string-based key-value pairs, IndexedDB supports larger amounts of structured data and asynchronous database operations.
It allows applications to store:
- User preferences and settings.
- Product and inventory records.
- Form submissions.
- Task and project information.
- Previously downloaded content.
- Offline transaction records.
- Pending synchronization requests.
IndexedDB works asynchronously, so database operations do not normally block the main JavaScript thread in the same way synchronous storage operations can.
IndexedDB vs. Local Storage
| Feature | IndexedDB | localStorage |
|---|---|---|
| Data Format | Structured data and objects | Strings |
| Storage Capacity | Generally larger, browser-dependent | Generally smaller |
| Operation Type | Asynchronous | Synchronous |
| Search | Supports indexes and key ranges | Manual searching |
| Transactions | Supported | Not supported |
| Offline Data | Suitable for larger datasets | Suitable for simple preferences |
| Complex Records | Supported | Requires serialization |
For applications with multiple records, searchable data, and offline workflows, IndexedDB is generally a better choice.
2. Understand the PWA Architecture
A PWA using IndexedDB combines browser storage, Service Workers, frontend components, and backend APIs.
Each component has a specific responsibility.
- Frontend: Displays application data and handles user interactions.
- IndexedDB: Stores structured information locally.
- Service Worker: Caches application resources and supports offline access.
- Backend API: Manages centralized application data.
- Synchronization Service: Transfers changes between local storage and the backend.
A typical architecture looks like this:
User
|
v
Progressive Web App
|
+---- Frontend Interface
|
+---- Service Worker
| |
| +---- Cache Storage
|
+---- IndexedDB
| |
| +---- Local Records
| +---- Pending Changes
| +---- User Preferences
|
v
Synchronization Service
|
v
Backend API
|
v
Central Database
IndexedDB and Cache Storage serve different purposes. Use IndexedDB for structured application records and Cache Storage for network resources such as HTML, CSS, JavaScript, and suitable images.
3. Choose the Right Technology Stack
The technology stack should support PWA development, browser database operations, backend communication, and offline synchronization.
| Layer | Recommended Technologies |
|---|---|
| Frontend | JavaScript, React, Vue.js |
| UI Framework | Tailwind CSS, Bootstrap |
| Local Database | IndexedDB |
| IndexedDB Library | Dexie.js, idb |
| PWA Features | Web App Manifest, Service Workers |
| Backend | Node.js, Python, Laravel |
| Central Database | PostgreSQL, MySQL, MongoDB |
| API Communication | REST APIs, GraphQL |
| Synchronization | Background Sync API where supported, foreground sync |
| Hosting | AWS, Google Cloud, Azure |
For many applications, Dexie.js is a practical choice because it provides a simpler interface for working with IndexedDB.
4. Design the IndexedDB Database Structure
Before implementing local storage, identify the records the application needs to maintain.
For example, an inventory management PWA may require the following object stores:
| Object Store | Purpose |
|---|---|
| products | Stores product information |
| categories | Stores product categories |
| customers | Stores customer records |
| orders | Stores locally created orders |
| pendingSync | Stores changes waiting for server synchronization |
| settings | Stores application preferences |
A sample database structure could look like this:
BhaktiInventoryDB
|
+---- products
| +---- id
| +---- name
| +---- price
| +---- quantity
|
+---- customers
| +---- id
| +---- name
| +---- phone
|
+---- orders
| +---- id
| +---- customerId
| +---- total
| +---- status
|
+---- pendingSync
+---- id
+---- entityType
+---- operation
+---- recordId
+---- createdAt
Use stable record identifiers and appropriate indexes for fields frequently used in searches.
Also consider database versioning. IndexedDB supports schema upgrades, allowing applications to add object stores and indexes as requirements change.
5. Set Up IndexedDB with Dexie.js
You can work directly with the browser’s IndexedDB API, but a library such as Dexie.js can simplify database creation and CRUD operations.
Install Dexie:
npm install dexie
Create a database file:
import Dexie from "dexie";
export const db = new Dexie("BusinessPWA");
db.version(1).stores({
products: "++id, name, category, price",
customers: "++id, name, email",
orders: "++id, customerId, status",
pendingSync: "++id, entityType, recordId, createdAt"
});
This creates a database named BusinessPWA with four object stores.
The ++id notation creates an auto-incrementing primary key. Other listed fields create indexes that can support efficient queries.
For production applications, define database versions carefully and implement upgrade logic when the schema changes.
6. Implement CRUD Operations
CRUD stands for Create, Read, Update, and Delete. These operations form the foundation of local data management.
Create Records
Add a new product to IndexedDB:
import { db } from "./database";
async function addProduct(product) {
try {
const id = await db.products.add(product);
return id;
} catch (error) {
console.error("Unable to add product:", error);
throw error;
}
}
Example usage:
await addProduct({
name: "Wireless Headphones",
category: "Electronics",
price: 2500,
quantity: 20
});
Read Records
Retrieve all products:
async function getProducts() {
return await db.products.toArray();
}
Retrieve a product using its ID:
async function getProductById(id) {
return await db.products.get(id);
}
Update Records
Update an existing product:
async function updateProduct(id, changes) {
return await db.products.update(id, changes);
}
Delete Records
Delete a product:
async function deleteProduct(id) {
return await db.products.delete(id);
}
These operations allow the application to manage local records without requiring a network request for every action.
7. Build an Offline-First PWA
Offline-first development means designing the application to remain useful even when internet connectivity is unavailable.
A typical workflow looks like this:
- The application loads its interface and essential resources.
- Previously downloaded records are retrieved from IndexedDB.
- Users create or update information locally.
- Changes are stored in IndexedDB.
- The application records operations that need synchronization.
- When connectivity returns, pending changes are sent to the backend.
- The server confirms the updates.
- The local database is updated with the latest server information.
This approach is useful for field workers, delivery teams, sales representatives, and businesses operating in areas with unreliable internet access.
The application should clearly indicate whether the user is working online, offline, or waiting for synchronization.
8. Create a Pending Synchronization Queue
When users modify data offline, the application needs to remember which records must be sent to the server later.
A synchronization queue can store pending operations.
Example:
async function queueSync(entityType, recordId, operation) {
await db.pendingSync.add({
entityType,
recordId,
operation,
createdAt: Date.now()
});
}
After saving a product locally, add its synchronization task:
async function saveProductOffline(product) {
const id = await db.products.put(product);
await queueSync(
"product",
id,
"upsert"
);
return id;
}
In production, the local record update and queue insertion should happen in a single IndexedDB transaction. This prevents a situation where the data is saved but its synchronization task is not.
The queue should also track retry attempts, error details, and operation identifiers to support reliable recovery.
9. Synchronize IndexedDB with the Backend
Local storage is useful for offline operations, but businesses often need a centralized database that keeps information consistent across multiple users and devices.
A synchronization service handles this communication.
Example:
async function syncPendingChanges() {
if (!navigator.onLine) return;
const tasks = await db.pendingSync.toArray();
for (const task of tasks) {
try {
const store = db[task.entityType + "s"];
const record = await store.get(task.recordId);
const response = await fetch(
"/api/sync",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
operationId: task.id,
entityType: task.entityType,
operation: task.operation,
record
})
}
);
if (!response.ok) {
throw new Error("Synchronization failed");
}
await db.pendingSync.delete(task.id);
} catch (error) {
console.error(
"Sync task failed:",
task.id,
error
);
}
}
}
This is a simplified example. A production synchronization system should include:
- Server-side authentication and authorization.
- Idempotent operation handling.
- Retry limits and backoff.
- Conflict detection.
- Deletion synchronization.
- Server acknowledgements.
- Validation of incoming and outgoing records.
Do not assume navigator.onLine guarantees that the backend is reachable. Handle actual request failures as well.
10. Handle Data Conflicts
Data conflicts occur when the same record is changed on multiple devices before synchronization.
For example:
- A salesperson changes a customer’s phone number offline.
- An administrator updates the same customer record from another device.
- Both devices reconnect and submit their changes.
The application needs a clear conflict-resolution strategy.
Common approaches include:
| Strategy | Description |
|---|---|
| Last Write Wins | Selects the latest accepted update using server-controlled timestamps |
| Version-Based Resolution | Detects changes using record version numbers |
| Manual Conflict Resolution | Allows users to review conflicting values |
| Field-Level Merging | Combines non-conflicting changes |
| Server Authority | Gives priority to specific server-side business rules |
For business applications, version-based conflict detection is often safer than blindly overwriting records.
For example, a record can include a version number that increments whenever the server accepts an update. The client submits the version it originally retrieved. If the version has changed, the server can reject the update and return the latest record for reconciliation.
11. Add Background Synchronization
Background synchronization can help PWAs send queued data when network connectivity returns.
The Background Sync API allows supported browsers to schedule synchronization through a Service Worker.
Example registration:
async function registerBackgroundSync() {
if (
"serviceWorker" in navigator &&
"SyncManager" in window
) {
const registration =
await navigator.serviceWorker.ready;
await registration.sync.register(
"sync-pending-data"
);
}
}
In the Service Worker:
self.addEventListener("sync", (event) => {
if (event.tag === "sync-pending-data") {
event.waitUntil(syncPendingChanges());
}
});
The syncPendingChanges() function must be implemented in the Service Worker environment and use compatible database access code.
Background Sync support varies across browsers and operating systems. Always provide a foreground synchronization fallback when users reopen the application or regain connectivity.
12. Manage Storage Limits and Browser Data
IndexedDB storage capacity is controlled by the browser and operating system. It is not unlimited.
Storage availability can vary depending on the device, browser, available disk space, and storage policies.
Important practices include:
- Monitor storage usage with
navigator.storage.estimate(). - Remove obsolete cached or local records.
- Avoid storing unnecessary duplicate data.
- Request persistent storage when appropriate.
- Handle quota-related errors.
- Provide recovery options when storage operations fail.
Example:
async function checkStorageUsage() {
if (!navigator.storage?.estimate) {
return null;
}
const estimate =
await navigator.storage.estimate();
return {
usage: estimate.usage,
quota: estimate.quota
};
}
You can also request persistent storage:
async function requestPersistentStorage() {
if (!navigator.storage?.persist) {
return false;
}
return await navigator.storage.persist();
}
A persistence request is not guaranteed to be granted. Applications should remain prepared for storage eviction or device-level data removal.
13. Protect Locally Stored Data
IndexedDB data is stored in the browser’s origin storage. It should not be treated as a secure vault for passwords, secret keys, or highly sensitive information.
Apply the following practices:
- Use HTTPS.
- Implement secure authentication.
- Validate data on the backend.
- Avoid storing sensitive payment information.
- Restrict access to authenticated application users.
- Protect against cross-site scripting (XSS).
- Clear user-specific local data during logout when appropriate.
- Apply suitable data retention policies.
- Avoid exposing sensitive records in application logs.
Client-side encryption may help protect certain stored information, but it does not eliminate risks from malicious scripts running within the same application context.
14. Test IndexedDB and Offline Functionality
Testing is essential because local database behavior and storage availability can vary across browsers and devices.
Important test cases include:
- Creating new records.
- Retrieving stored records.
- Updating existing data.
- Deleting records.
- Reloading the application.
- Operating without internet connectivity.
- Reconnecting and synchronizing pending changes.
- Handling duplicate synchronization requests.
- Resolving conflicting updates.
- Recovering from failed network requests.
- Handling storage quota errors.
- Upgrading the database schema.
Test the application in Chrome, Edge, Firefox, and supported mobile browsers. Also test Service Worker behavior and IndexedDB operations in private browsing or restricted storage environments where applicable.
15. Common Development Challenges
| Challenge | Recommended Solution |
|---|---|
| Complex IndexedDB operations | Use Dexie.js or another suitable wrapper |
| Data synchronization failures | Implement retry and recovery mechanisms |
| Conflicting updates | Use version-based conflict detection |
| Browser storage limitations | Monitor usage and handle quota errors |
| Offline application failures | Cache essential resources and maintain local records |
| Database schema changes | Implement versioned database upgrades |
| Duplicate server updates | Use idempotency keys |
| Sensitive local data | Apply access controls and data minimization |
Addressing these issues during development helps create a more reliable offline-capable PWA.
16. Estimate Development Cost
The cost of building a PWA with IndexedDB depends on application complexity, offline requirements, data volume, backend integrations, and synchronization logic.
| Development Scope | Estimated Cost (USD) |
|---|---|
| Basic PWA with IndexedDB storage | $3,000–$6,000 |
| PWA with CRUD and offline support | $6,000–$10,000 |
| Advanced PWA with backend synchronization | $10,000–$20,000 |
| Enterprise offline-first application | $20,000+ |
These are indicative planning estimates, not verified market quotations. Hosting, maintenance, security testing, and third-party integrations may involve additional costs.
17. Final Development Checklist
Before launching your IndexedDB-powered PWA, review the following:
- Responsive and installable PWA architecture.
- IndexedDB database structure.
- Versioned database schema.
- CRUD operations.
- Service Worker resource caching.
- Offline data access.
- Pending synchronization queue.
- Backend synchronization API.
- Conflict-resolution strategy.
- Background and foreground synchronization.
- Storage usage monitoring.
- Local data security.
- Cross-browser testing.
Conclusion
Building a PWA with IndexedDB for local data storage allows businesses to create applications that remain useful even when internet connectivity is limited.
By combining IndexedDB, Service Workers, modern JavaScript frameworks, and backend synchronization APIs, developers can build applications that support local data management, offline workflows, and reliable synchronization.
The most important considerations are a well-designed database structure, efficient CRUD operations, conflict handling, storage management, and secure synchronization.
A properly designed IndexedDB architecture can improve application responsiveness while giving users more flexibility to work across different network conditions.
Looking to build a custom PWA with IndexedDB and offline data storage? Dotcube Technologies can help design and develop a Progressive Web App tailored to your business requirements.
Contact Dotcube Technologies: https://www.dotcubetechnologies.com/#contact




