Courses Blog About
Post updated at  

IndexedDB: A client database for lightning and offline applications

compression

Imagine: a user logs into your web application - an online store, a fintech service, or a gaming platform — on the subway, where the connection is unstable. The page takes forever to load, the shopping cart is not updated, and key functionality is unavailable. The result? Irritation and a closed tab. In Russia, with its vast territory and different communication quality, this is not a rare case, but a daily reality for millions.

How can you save the user and give them a seamless experience, even when the network has failed?

The answer is the transition from server-first to client-first architecture.

And the heart of this client-side approach is IndexedDB.

What is IndexedDB?

IndexedDB (Indexed Database API) is a full-fledged, NoSQL-like database built directly into the user’s browser. It’s not just “another storage” like localStorage or Cookies.

IndexedDB is like a built—in warehouse inside your browser. If localStorage is a small safe for several securities (key-value), then IndexedDB is a huge logistics center where you can store entire catalogs of goods, order history, draft documents, and complex data structures, and then instantly find what you need for any parameter.

Key features that are important to understand

How does IndexedDB work?

The principle of operation of IndexedDB differs from simple key-value repositories. Here are his basic concepts

A simple analogy: Imagine that you are a librarian. The database is the entire library. Object storages are shelving (fiction, scientific, periodicals). Indexes are catalog cards sorted by title, author, or year of publication. A transaction is the process of giving a book to a reader: you find a book in a catalog (index), go to a shelf (storage), pick it up and mark it in a journal — all these actions either occur entirely or do not occur at all.

IndexedDB in the context of the Client-First approach

Client-First is an architectural pattern where the main logic and data are first processed on the client side, and the server acts as a synchronized backend.

1. Offline Work and Resilience

Your app works without any network at all. The user can view the cached product catalog, fill the shopping cart, and edit the profile. All data is written to IndexedDB. As soon as the connection is restored, a special background process synchronizes the changes with the server.

2. Lightning-fast performance

The data is already on the user’s device. You don’t need to wait for a network request to draw the interface. This drastically reduces the Time to Interactive (TTI).

3. Reducing server load

Fewer API requests to get the same data (for example, city directories or a list of categories). Static data is loaded once and then taken from the local database.

4. Effective management of big data

If your application works with large datasets (for example, graphs, analytics, catalogs with thousands of items), loading them all into RAM (as in Redux) is inefficient. IndexedDB allows you to work with data in chunks, through cursors.

How to use IndexedDB? A practical example for your project

Theory without practice is dead. Let’s look at a basic example of working with IndexedDB in JavaScript.

Task: Create a database for caching online store products.

// Opening or creating a database
const request = indexedDB.open('MyShopDB', 1); // 'MyShopDB' - name, 1st version

let db;

// It is triggered if the database needs to be created or updated.
request.onupgradeneeded = function(event) {
  db = event.target.result;

  // Creating a repository of 'products' objects with the 'id' key
  const productStore = db.createObjectStore('products', { keyPath: 'id' });

  // Creating an index for searching by category 'category'
  productStore.createIndex('by_category', 'category', { unique: false });
};

// It is triggered when the database is opened successfully.
request.onsuccess = function(event) {
  db = event.target.result;
  console.log('База данных открыта');
};

// It is triggered by an error
request.onerror = function(event) {
  console.error('Ошибка базы данных:', event.target.errorCode);
};

// A function for adding a product
function addProduct(product) {
  // Creating a write transaction for the 'products' storage
  const transaction = db.transaction(['products'], 'readwrite');
  const store = transaction.objectStore('products');

  const request = store.add(product);

  request.onsuccess = function() {
    console.log('Товар добавлен в IndexedDB');
  };

  request.onerror = function() {
    console.log('Ошибка при добавлении товара');
  };
}

// A function for getting all products by category
function getProductsByCategory(category) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction(['products'], 'readonly');
    const store = transaction.objectStore('products');
    const index = store.index('by_category'); // Using the index

    // We receive all products with the specified category
    const request = index.getAll(category);

    request.onsuccess = function() {
      resolve(request.result);
    };

    request.onerror = function() {
      reject(request.error);
    };
  });
}

// Usage example
const newProduct = { id: 123, name: 'Смартфон', category: 'electronics', price: 29999 };
addProduct(newProduct);

// Later, to get all the electronics
getProductsByCategory('electronics').then(products => {
  console.log(products); // Displays an array of products, including our smartphone
});

What it can be used for right now:

Best practices and pitfalls

Conclusion

IndexedDB is not a niche technology, but a powerful tool for creating a modern, competitive web application, especially in the context of the Russian market with its connectivity specifics. Switching to a client-first approach using IndexedDB allows you to:

Start small by implementing catalog caching or shopping cart. You will immediately see how your product will become faster, more reliable and more independent.

frontline

FrontLine

Join us in telegram

Other interesting posts in a convenient format

Subscribe

More interesting on the topic