Course contentsShow
← Web Development
Lesson 785 of 2,98214. Browser StorageFree lesson

Database Versioning and onupgradeneeded

Learn how database versions work and when the upgrade event fires for schema changes.

Database Versioning and onupgradeneeded

You'll learn how IndexedDB uses version numbers to safely update your database structure when your app evolves.


Why Databases Need Versions

Think of a database version like a building blueprint revision number. When you first open an IndexedDB database, you assign it a version (usually 1). If you later need to add new object stores or change the structure, you increment the version number. IndexedDB uses this number to know when the database schema needs updating.

When the Upgrade Event Fires

The onupgradeneeded event fires automatically in two situations:

  1. First time creation: When you open a database that doesn't exist yet
  2. Version change: When you open an existing database with a higher version number than what's stored

This event is your only opportunity to modify the database structure—you cannot create or delete object stores outside of this event handler.

How It Works

When you call indexedDB.open('myDB', 2), IndexedDB compares the requested version (2) with the stored version. If stored version is 1 (or doesn't exist), onupgradeneeded fires, giving you a chance to update the schema before any other operations proceed.

Inside the onupgradeneeded handler, you can:

  • Create new object stores
  • Delete old object stores
  • Modify indexes

The event object provides oldVersion and newVersion properties, letting you write conditional upgrade logic for users migrating from different versions.

Key Takeaway: Database versioning in IndexedDB ensures structural changes happen safely through the onupgradeneeded event, which fires when creating a new database or opening an existing one with a higher version number—this is the only time you can modify the database schema.