This gist provides functions to import and export data from an IndexedDB database as JSON. It's based on Justin Emery's indexeddb-export-import
package, but applies some adjustments that reflect better on the current browser landscape (i.e. better developer ergonomics but no support for Internet Explorer).
For each of the provided functionalities, you need a connected IDBDatabase
instance.
import { idb } from 'some-database'
import { exportToJson } from 'idb-backup-and-restore.js'
exportToJson(idb)
.then(result => {
console.log('Exported JSON string:', result)
})
.catch(error => {
console.error('Something went wrong during export:', error)
})
import { idb } from 'some-database'
import { serializedData } from 'some-serialized-data'
import { importFromJson } from 'idb-backup-and-restore.js'
importFromJson(idb, serializedData)
.then(() => {
console.log('Successfully imported data')
})
.catch(error => {
console.error('Something went wrong during import:', error)
})
Depending on your use case, it can be reasonable to clear a database before importing serialized data:
import { idb } from 'some-database'
import { serializedData } from 'some-serialized-data'
import { importFromJson, clearDatabase } from 'idb-backup-and-restore.js'
clearDatabase(idb)
.then(() => importFromJson(idb, serializedData))
.then(() => {
console.log('Successfully cleared database and imported data')
})
.catch(error => {
console.error('Could not clear & import database:', error)
})
Okay, that should be relatively straightforward, under one condition: You'll still have the IndexedDB on the new machine, even though it may be empty. This is necessary because the export script from above can only export the DB's data, not its strucure.
For both exporting and importing data, you'll need an IndexedDB instance. Say you're wanting to back up the
foo
database, then you could get an instance in the console like this:Export:
exportToJson
function (without the prependedexport
statement), paste it into the DevTools Console and hitEnter
.await exportToJson(db)
copy($_)
to copy the return value of the previous command (= the exported data) to your clipboard.Import:
Copy the
importFromJson
function (without the prependedexport
statement), paste it into the DevTools Console and hitEnter
.Invoke it with the IndexedDB instance and the exported data as parameters:
await importFromJson(db, exportedString)
.Note that you actually have to pass the exported data as a string, not as a JSON object. For example: If you exported and empty database
{}
, you'd have to pass into the function the following:await importFromJson(db, '{}')
.This should be it. Probably test it before you actually rely on it. 🙂