A real database inside the browser: IndexedDB local storage, explained plainly
localStorage only stores strings and has no indexes. IndexedDB is a real database in the browser: structured data, far larger capacity, indexes, and transactions. Following MDN's Using IndexedDB, IDBDatabase, and IDBObjectStore: the five-step routine, opening, upgrades, keys, indexes, transactions, add versus put, get, cursors, ranges, and multi-tab upgrades.

Let me set the boundaries first. This site already has a localStorage guide, covering the simplest way to store things in the browser: string key-value pairs, saved and read at will. But localStorage has three ceilings: it only stores strings, so objects have to be turned into JSON strings first; its capacity is only a few megabytes, so it cannot hold much; and it has no indexes, so finding one record by name means reading all the data out and comparing it one by one. IndexedDB is a real database inside the browser: it stores structured data like objects, arrays, and files directly, holds far more, can build indexes to search by field, and uses transactions so that a group of operations either all succeeds or all fails. The "Greenstone Cafe" used below is the same fictional practice project as in earlier guides: a small web tool that takes orders for a street-corner cafe. Earlier guides covered its styling, its arithmetic, and how to wrap its work into functions; this one covers how its order page stores orders in the browser itself: orders still work offline, they are still there when the page is closed and reopened, and staff can search by table number, dish name, or time. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. All syntax and behavior about IndexedDB comes from three official MDN documents: "Using IndexedDB", "IDBDatabase", and "IDBObjectStore"; the sources are listed in the meta information and the evidence record for this article. After reading it, you should be able to do four things: open a database and build a store by the five-step routine, create, read, update, and delete through transactions, search data with indexes and cursors, and handle version upgrades and multiple tabs. This guide does not cover syncing data to a server, nor the full use of wrapper libraries like Dexie or localForage, mentioning them only where needed; it also does not cover Web SQL, an old technology that has been abandoned.
Step 1: Learn the five steps first: the fixed routine of IndexedDB
IndexedDB looks wordy at first, but MDN's Using IndexedDB tutorial gives a five-step routine right at the start, and the whole article is an expansion of those five steps; once you know the routine, you will not get lost. Step one, open a database. Step two, create an object store in the database. Step three, start a transaction and make a request to do some database operation, like adding or retrieving data. Step four, wait for the operation to complete by listening to the right kind of DOM event. Step five, do something with the results, which can be found on the request object. An object store is the "table" of IndexedDB, a place to hold data; one database can hold any number of object stores, and every value stored in one is paired with a key. Keys can be given in three ways: name a keyPath when the store is created, so one property of the object becomes the key; or turn on auto-increment, so the browser numbers keys automatically; or set neither, and pass a separate key each time you store data. On the cafe order page, the database can be called cafeOrders, the object store orders, and each order is an object holding a table number, a dish name, a quantity, and an order time, with the order number as the key. The most counter-intuitive part of the five steps is step four: every IndexedDB operation is asynchronous. Calling a method does not hand you the result at once; it hands you a request object first, and only after the browser finishes the work in the background does a success or error event fire, with the result available in the callback. That is completely different from the synchronous style of localStorage, where setItem stores at once and getItem returns at once. The most common beginner mistake with IndexedDB is reading the result before the request has finished; what you read is always undefined. The check for this section: for any IndexedDB operation, first ask "did I wait for the event?" If you read the result without waiting, the code is wrong.
Step 2: Opening the database: the name and the version decide
The whole flow starts with opening the database, and it takes a single line: const request = window.indexedDB.open("MyTestDatabase", 3). MDN's tutorial makes a point of saying that opening is itself a request: calling open does not open the database right away, nor does it start a transaction right away. It returns an IDBOpenDBRequest object first, and success or failure arrives as an event to handle. The second argument of open is the version of the database, and the version decides the database schema: which object stores exist and what each one looks like. If the database does not exist yet, open creates it first, then fires an onupgradeneeded event, and you build the stores inside that event's handler; if the database already exists but you pass a higher version number, onupgradeneeded fires at once, letting you provide the new schema in its handler. Version numbers must be integers, and MDN warns explicitly that passing 2.1 and 2.4 both rounds to 2, so trying to upgrade from 2.1 to 2.4 upgrades nothing and onupgradeneeded never fires. There is one more rule for versions: if the version stored on disk is higher than the one you are trying to open, you get a VER_ERR error, and that case must be caught by the error handler. On the cafe order page, the database can launch as cafeOrders, version 1, holding a single orders store; later, when you want a dishes store for the menu, change the version to 2 and build the dishes store inside onupgradeneeded, leaving the old orders store untouched. The first thing to do after opening is to attach success and error callbacks to the request: handle the failure case in request.onerror, and in request.onsuccess save the result, which is an IDBDatabase instance, the entry point for everything that follows. MDN also notes that the most likely reason opening fails is that the user did not give the web app permission to create a database; that is by design, since browsers do not want advertising networks or malicious sites stuffing data onto a user's computer. The check: right after the open call, confirm all three callbacks are attached, onupgradeneeded, onsuccess, and onerror. Miss one, and you will be blind when an upgrade or a failure happens.
Step 3: onupgradeneeded: structure can only change here
The structure of a database, creating or deleting object stores, building or removing indexes, can only change inside the onupgradeneeded callback, and MDN repeats this through the tutorial. The form is request.onupgradeneeded = (event) =>, and inside the callback you take the database first: const db = event.target.result, then call db.createObjectStore to build a store. MDN's example is db.createObjectStore("name", { keyPath: "myKey" }), a store called name whose key is the myKey property of the object. The cafe example can be db.createObjectStore("orders", { keyPath: "orderId" }), a store called orders whose key is the orderId property of the order object. Three rules govern structural changes. First, only after onupgradeneeded exits successfully does the open request's onsuccess callback fire; the order cannot be shuffled. Second, a store that already exists does not need rebuilding; only build new stores and delete ones no longer needed. Changing an existing store's keyPath means deleting the old store and creating it again with the new options, at the cost of all the data inside it; to keep that data, read it out and save it elsewhere first. Third, creating a store with a name that already exists throws an error, and so does deleting a store with a name that does not exist. MDN's IDBDatabase reference adds the matching methods: createObjectStore builds a store, and deleteObjectStore destroys the store with the given name, along with any indexes that reference it. One detail is easy to miss: the database connection you get in onupgradeneeded and the one you get in onsuccess are the same database object, but structural changes can only happen in the former; calling createObjectStore in onsuccess throws an error at once. On the cafe order page, build the orders store in onupgradeneeded when the database is created the first time; when a later feature needs another store, only bump the version number and only build the extra store in onupgradeneeded, touching nothing anywhere else. The check: for any structural change, first ask "am I inside onupgradeneeded right now?" If not, do not touch it.
Step 4: Primary keys: the four combinations of keyPath and auto-increment
The biggest difference between an object store and a table is that every record needs a key, and the key must be unique. MDN's tutorial explains the four combinations of the keyPath and autoIncrement options in a table, and once you understand that table, you will not pick the wrong setup when creating a store. First, with neither set, the store can hold any kind of value, even primitive values like numbers and strings, but you must supply a separate key argument whenever you add a new value. Second, with only keyPath set and no auto-increment, the store can only hold JavaScript objects, and the objects must have a property with the same name as the key path; with a keyPath of ssn, every object stored must have an ssn property. Third, with only auto-increment set and no keyPath, the store can hold any kind of value, the key is generated for you automatically, and you can still supply a separate key argument if you want a specific key. Fourth, with both set, the store can only hold objects; usually a key is generated and the generated key is stored in the object under the key path property, but if such a property already exists, its value is used as the key instead of generating a new one. MDN's example is customer data: the keyPath is ssn, because a social security number is guaranteed to be unique, created as db.createObjectStore("customers", { keyPath: "ssn" }). The auto-increment counter starts at 1 and goes up by 1 with each added record, and it never goes down: deleting a record, or even clearing all records from the store, never affects the key generator, as MDN states plainly. Do not expect the key numbers to start again from 1 after clearing. On the cafe order page, the order number is naturally unique, so a keyPath on the order number fits best: db.createObjectStore("orders", { keyPath: "orderId" }). If the order object has no ready-made unique number, use auto-increment instead, db.createObjectStore("orders", { autoIncrement: true }), and let the browser number the orders. The check: if the object already has a unique field, use keyPath; if not, use auto-increment; if you want both, first think through whether the generated key could clash with a value already in the object.
Step 5: Indexes: search by name or email without reading the whole store
Searching by primary key alone is not enough: the order page needs to find orders by table number, by dish name, and by time, and the primary key is the order number, which none of those searches can use. MDN's answer is indexes: an index is built on an object store and lets you look up values using a property of the stored object, rather than the object's key. An index can only be created inside onupgradeneeded, written as objectStore.createIndex("name", "name", { unique: false }): the first argument is the index name, the second is the property it watches, the third holds the options. MDN's customer example builds two indexes: a name index with unique set to false, because two people can share a name; and an email index with unique set to true, because no two customers may share an email address, and a unique index enforces that when data is stored. There is one hard rule for indexes: they can only be created on a store that holds objects, not on one holding primitives. Reading through an index starts by taking the index object, then calling get: const index = objectStore.index("name"), then index.get("Donna"), and in the success callback event.target.result is that customer record. The name index is not unique, so one name can match several records, and get returns the one with the lowest key value; to get them all, use a cursor, covered in step nine. An index can also be built on several properties, a compound index: createIndex("name_email", ["name", "email"]), and searching passes an array of values in the same order, index.get(["Donna", "donna@home.org"]). MDN's example verifies this, returning the record with ssn 555-55-5555, name Donna, age 32, and email donna@home.org. On the cafe order page, the orders store can carry two indexes: a table index for searching by table number, unique false, since one table can place several orders; and a dish index for searching by dish name, unique false as well, since one dish can appear in many orders. The check: if the search condition is not the primary key, first ask "is there an index on this field?" If not, add one in the next upgrade instead of reading the whole store and comparing records one by one.
Step 6: Transactions: readonly and readwrite each do their own job
Everything you do in IndexedDB always happens in the context of a transaction, and MDN's IDBDatabase reference states it at the top: all objects in IndexedDB, including object stores, indexes, and cursors, are tied to a particular transaction, so you cannot execute commands, access data, or open anything outside of a transaction. A transaction is opened with db.transaction, taking two arguments: the names of the object stores to access, as a single string or an array; and the mode. There are three modes: readonly, readwrite, and versionchange. Changing the schema needs versionchange mode, and you never open that one yourself; it is opened by calling IDBFactory.open with a version specified. Reading records can use readonly or readwrite; changing records must use readwrite. With no mode given, the default is readonly, so reading data only needs db.transaction("customers"), while writing data must spell out db.transaction(["customers"], "readwrite"). MDN adds two tips for speed: first, when defining the scope, specify only the object stores you need, so multiple transactions with non-overlapping scopes can run concurrently; second, only specify readwrite when necessary, since you can run many readonly transactions with overlapping scopes at the same time, but only one readwrite transaction for an object store. On the cafe order page, checking orders and listing the menu use readonly, so several pages or tabs can read at the same time without blocking each other; placing, changing, or deleting an order uses readwrite, letting one write transaction into a store at a time and the next one in after it finishes. A transaction fires three kinds of events: error, abort, and complete. Error events bubble from the request to the transaction and then to the database object, so instead of adding an error handler to every request, you can add one handler on the database object with db.onerror. The default behavior of an error is to abort the whole transaction, unless you first call stopPropagation on the error event; if you do not handle an error, or you call abort on the transaction, the transaction is rolled back and an abort event fires; after all pending requests have completed, you get a complete event. The check: before doing anything, ask whether this operation reads or writes. Read with readonly, write with readwrite; a write in a read-only transaction fails outright.
Step 7: A transaction lives briefly: return to the event loop and it dies
The lifetime of a transaction is the easiest place for beginners to crash in IndexedDB, and MDN's tutorial gives it a section of its own. Transactions are tied very closely to the event loop: if you make a transaction and return to the event loop without using it, the transaction becomes inactive. The only way to keep it active is to make a request on it. When the request finishes you get a DOM event and another opportunity to extend the transaction during that callback. Return to the event loop without extending it, and it goes inactive again. As long as there are pending requests, the transaction remains active. MDN also gives the diagnostic clue: if you start seeing TRANSACTION_INACTIVE_ERR error codes, that is where you went wrong. The classic crash looks like this: open a readwrite transaction, then call setTimeout, or wait for a network request to return before writing to the store; by the time your callback runs, the transaction is long dead. The correct form chains every request inside the same transaction's callbacks: the first request's onsuccess fires the second request, the second's onsuccess fires the third, and the transaction keeps going by relay. One more rule goes with it: after a transaction completes, using it to open an object store throws an error, since the object store object belongs to the transaction, and when the transaction dies, the store goes with it. On the cafe order page, the three things placing an order needs, adding the order, deducting stock, and recording the transaction, must sit in one readwrite transaction, each request fired from the previous request's callback; never write "wait for the network to return the dish price, then open a transaction and write", because by the time the network returns, the transaction is gone. The check: when writing IndexedDB code, first ask "are all my requests inside the same transaction's callback chain?" Anywhere a setTimeout, an await, or a network request sits in between, the transaction may already be dead.
Step 8: Adding: add and put have different jobs
Adding data to a store uses a pair of methods, add and put, with a clear division of labor that MDN's tutorial and the IDBObjectStore reference draw sharply. add is for new records: it requires that no object already be in the database with the same key, or it errors. Its request result is the key of the value that was added; for a store whose keyPath is ssn, adding a customer record gives back that record's ssn as the result. put is "update if present, add if not": if a record with the same key already exists it is overwritten, and if not, a new one is added. MDN's tutorial example is the customer data: an array customerData holds two records, Bill and Donna, with ssns 444-44-4444 and 555-55-5555. After the store is created in onupgradeneeded, objectStore.transaction.oncomplete confirms the store is ready, then a readwrite transaction loops over objectStore.add(customer) to write both records in. MDN's IDBObjectStore reference adds one more fact: add and put store a structured clone of the value, a copy made before storing, so changing the original object afterwards does not change the copy in the store. On the cafe order page, placing an order uses add: the order number is freshly generated, so the store cannot already hold it, and an add failure means the order number collided, which is exactly the problem you want to catch. Changing an order uses put: staff change one order's quantity, take the order number, and put the order back; present, it is overwritten, absent, it is added as a new order. Both methods only work inside a readwrite transaction; calling them in a readonly transaction fails outright. The check: before writing data, ask whether a record with this key could already exist in the store. If it cannot, use add; if it could, use put. Pick wrong, and you either error for no reason or quietly overwrite someone else's data.
Step 9: Reading: get, getAll, and cursors each do their own job
There are three ways to read data, and MDN's tutorial gives them in order from simplest to fullest. The first is get, taking one record by key: objectStore.get("444-44-4444"), and in the success callback request.result is that record; MDN's example verifies it, returning the customer record named Bill. Reading only needs the default readonly transaction, and the code can be shortened: db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess, with event.target.result holding the result. The second is getAll, taking everything at once: objectStore.getAll().onsuccess, with event.target.result holding an array of all the records. MDN spells out the trade-off with cursors: a cursor's value property is created lazily, so reading only keys with a cursor is much more efficient; getAll creates all the objects at once, so when you want an array of all the objects in a store, use getAll. The third is a cursor with openCursor, walking through records one by one: objectStore.openCursor().onsuccess, where event.target.result is the cursor, cursor.key is the key, cursor.value is the whole record, and calling cursor.continue() moves on; at the end of the data, or when nothing matched, the result is undefined, so the callback must check whether the cursor is empty. MDN's example collects all customers into an array: while the cursor exists, push its value and continue; when the cursor is empty, everything has been collected, and the code prints Got all customers. A cursor also takes arguments: the first is an IDBKeyRange limiting the range of keys, the second is the direction, ascending by default, and passing "prev" walks in descending order. On the cafe order page, taking one order by its number uses get, listing all orders when the page opens uses getAll, and computing subtotals one by one or rendering a list row by row uses a cursor; when the data is large enough that reading it all at once would freeze the page, a cursor processing one record at a time is steadier. The check: know the key, use get; want the whole array, use getAll; want to process records one by one, or the data is too big, use a cursor. Do not mix the three up.
Step 10: Updating and deleting: take it out, then put it back
IndexedDB has no "change one field directly" operation. The standard flow for updating a record is three steps: get it out first, change the property on the object, then put it back. MDN's tutorial gives the full example: open a readwrite transaction, take the customers store, call get("444-44-4444"), and in the success callback event.target.result is Bill's record. Change its age from 35 to 42, then call objectStore.put(data) to put it back, and the put success callback confirms the update is done. This needs a readwrite transaction, because it writes data; calling put in a readonly transaction fails outright. Deleting one record is simpler: objectStore.delete("444-44-4444") removes the record by the key passed in, and the success callback confirms it is gone. MDN's IDBObjectStore reference lists two more companion methods: clear() deletes all current records out of a store, and count() returns the total number of records matching the key or key range given, or the total number of records in the store when no argument is given. Before deleting, think about one thing: delete and clear cannot be undone; once deleted, a record is gone, unlike put, which can still be recovered. On the cafe order page, changing an order follows this flow: staff change one order from 2 portions to 3, get the order object out first, change count to 3, then put it back. Cancelling an order is delete by order number. Closing up for the day uses clear to empty the day's orders store in one go. Checking how many orders were placed today uses count() to read the total, without reading all the orders out and counting them. The check: before changing data, ask whether the record in hand was just taken from the store. If not, get it first and then put it back; never assemble an object from memory and put it straight in, or you may overwrite other fields with nothing.
Step 11: Ranges and direction: IDBKeyRange and how cursors walk
A cursor can do more than walk from start to finish: it can walk only part of the data, or walk backwards, and MDN's tutorial explains the range syntax with IDBKeyRange. IDBKeyRange.only("Donna") matches only the key "Donna"; lowerBound("Bill") matches "Bill" and anything past it, including "Bill"; lowerBound("Bill", true) also starts at "Bill" but does not include it, because the second argument true means an open bound that excludes the given value; upperBound("Donna", true) matches anything up to, but not including, "Donna"; bound("Bill", "Donna", false, true) matches anything between "Bill" and "Donna", including "Bill" but not "Donna". A range object is passed as the first argument of openCursor or openKeyCursor, for example index.openCursor(boundKeyRange). Direction is the second argument: ascending by default, and passing "prev" walks in descending order. To change direction without limiting the results, pass null as the first argument, like objectStore.openCursor(null, "prev"). Cursors on an index come in two kinds: a normal cursor with openCursor, where cursor.key is the index property value and cursor.value is the whole object; and a key cursor with openKeyCursor, where cursor.key is still the index property value but cursor.primaryKey is the primary key, and there is no way to get the rest of the stored object directly, which fits when you only want keys. An index can also hold duplicate names, since the name index is not unique, and get then returns only the entry with the lowest key value; to filter out duplicates while iterating a cursor over an index, pass "nextunique" or "prevunique" as the direction, and the entry with the lowest key is always the one returned. On the cafe order page, the two most useful range searches are finding one day's orders by bounding the day's start and end times, and listing the newest orders first by table number with openCursor(null, "prev") walking from large to small. The check: before calling a cursor, ask whether you want everything, a slice, or a backwards walk. Everything needs no arguments, a slice takes an IDBKeyRange, and backwards takes "prev"; three answers, three forms.
Step 12: Version upgrades, multiple tabs, a checklist, and a breakdown chart
Upgrading a database raises one more question: a user may have the old version of the app open in one tab and load the new version in another. MDN's tutorial describes the handshake: when the new page calls open with a greater version, all other open databases must explicitly acknowledge the request before changes can start, and until they do, an onblocked event fires, saying in effect "some other tab has this site open, please close it first". The old page's job is to attach an onversionchange handler to the database, close the connection with db.close() when notified, and tell the user to reload or close the tab; without this, the upgrade waits until the user closes the tab on their own. One more error goes with it: an already opened app that tries to open the database with an outdated version triggers a VersionError. Beyond upgrades, MDN covers two traps that are easy to step into. First, IndexedDB uses the same-origin principle: a store belongs to the origin of the site that created it, typically the site domain or subdomain, and no other origin can access it. Second, never tie database transactions to unload events: because transactions are asynchronous, transactions created in an unload event handler are aborted before they can execute, so saving data when the browser closes does not work. The right approach is to write to the database as soon as data changes, instead of saving it all up for closing time; and a two-step job like clearing a store and writing a new list must sit in a single transaction, or the browser may close after the clear but before the write, leaving an empty database. The chart below shows a fictional breakdown of 100 IndexedDB mistakes in one month on the Greenstone Cafe order page. The numbers are invented examples, matched against the traps from the eleven steps above: forgetting to open a readwrite transaction and sending a write into a readonly one, 21 times, the most; changing only the version number in open without adding the structure in onupgradeneeded, 18 times; using add on a key that already exists, when put was the right call, 16 times; letting a transaction sit idle back to the event loop so it was dead by the time of the next write, 13 times; forgetting to call continue on a cursor and reading only the first record, 11 times; building an index outside an upgrade, 9 times; pulling the whole store with getAll at once and freezing the page on large data, 7 times; saving data in an unload handler when the browser closed, with the transaction never finishing, 5 times. 21 + 18 + 16 + 13 + 11 + 9 + 7 + 5 = 100, and the books balance.
After writing the order page's local storage logic, run through these seven questions before launch. First, are the three open callbacks attached? Missing onupgradeneeded, onsuccess, or onerror leaves you blind when an upgrade or a failure happens. Second, are structural changes all inside onupgradeneeded? Creating stores, creating indexes, and deleting stores only work there; doing them anywhere else throws an error outright. Third, is the transaction mode right? Read with readonly, write with readwrite; a wrong mode makes the write fail outright. Fourth, is the transaction still alive? Requests must be chained in the same transaction's callbacks, and a setTimeout, an await, or a network request in between may already have killed it. Fifth, did you pick add or put correctly? A key that cannot exist takes add, a key that might exist takes put; picking wrong either errors for no reason or quietly overwrites someone else's data. Sixth, did you pick the right way to read? Know the key, use get; want the whole array, use getAll; want to process records one by one, use a cursor; and if an index cannot answer the query, add the index in the next upgrade. Seventh, is the upgrade and close handshake written? onblocked should tell the user to close old tabs, onversionchange should close the connection, and a write transaction must never be tied to an unload event. After these seven questions, look back at the three MDN documents: Using IndexedDB is the tutorial for the whole flow, the IDBDatabase reference is the manual for the database connection itself, and the IDBObjectStore reference is the list of every method on a store. They have different jobs, so do not go to the wrong one when you have a question: for how a flow should be written, go back to the tutorial; for what a method is called, go to the object store reference; for what properties a database connection has, go to the IDBDatabase reference. One last reminder: syncing data to a server and the full use of wrapper libraries like Dexie and localForage, none of which this guide covers, each have their own traps. When you really need them, read the matching official documentation first instead of writing from memory.
Comments (0)
Sources
Related articles
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.
Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.
A selector is the first part of a rule: it decides who the styles land on. This guide follows MDN's Basic CSS selectors, Attribute selectors, and Pseudo-classes and pseudo-elements: type, class, ID, selector lists, universal, attribute selectors, pseudo-classes, pseudo-elements, chaining them together, plus a checklist for when a style does not show up.