AI Workshop: learn to build apps with AI →
IndexedDB: Creating a database and a store

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Before using the IndexedDB API, always make sure you check for support in the browser. Even though IndexedDB is widely available nowadays, you never know which browser the user is using.

Here’s how to check for it, using 'indexedDB' in window:

(() => {
  'use strict'

  if (!('indexedDB' in window)) {
    console.warn('IndexedDB not supported')
    return
  }

  //...we can safely run IndexedDB code
})()

When we create a database, we must initialize a store. If you are familiar with relational databases like MySQL, a store is like a table.

(async () => {
  //...

  const dbName = 'mydbname'
  const storeName = 'store1'
  const version = 1

  const db = await openDB(dbName, version, {
    upgrade(db, oldVersion, newVersion, transaction) {
      const store = db.createObjectStore(storeName)
    }
  })
})()

You can check if an object store already exists before creating it by using the objectStoreNames property and its contains() method:

const storeName = 'store1'

if (!db.objectStoreNames.contains(storeName)) {
  db.createObjectStore(storeName)
}

Lessons in this unit:

0: Introduction
1: Loading the idb library
2: ▶︎ Creating a database and a store
3: Adding data into a store
4: Retrieving data from a store
5: Deleting data
6: Migrations
7: Unique keys