When a browser app needs to keep SQLite changes after a page reload, it must save the database beyond the page’s memory. sql.js runs SQLite in the browser, and its export function returns bytes that an app can store in IndexedDB.
This article explains how to create and query a database with sql.js, then save and reopen it.
TL;DR: Run SQLite in the browser with sql.js
sql.js runs SQLite inside JavaScript, and you must export its in-memory database if you want to keep changes after a page reload.
- Install the npm package and serve its WebAssembly file.
- Use db.exec() to run queries.
- Save db.export() bytes in IndexedDB, then pass them to new SQL.Database() when reopening.
What is sql.js?
sql.js is a JavaScript library that compiles SQLite to WebAssembly, so a browser can create and query a SQLite database without a database server. Its database lives in memory while the page is open.
WebAssembly is a binary format that browsers can run alongside JavaScript. sql.js loads a JavaScript wrapper and a matching WebAssembly file, then exposes SQLite through a database object. That object works with a complete database held in memory, so the page must load the file or exported bytes before it can query saved data.
The database is not written to browser storage automatically. The sql.js documentation exposes an export method that returns the database as a byte array. Your app decides where those bytes go.
How to use sql.js in a browser
I ran the following query with the installed sql.js package. It creates a table, inserts one parameterized value, queries it, exports the database, and opens that export again.
Step 1: Initialize sql.js and create a table
Install sql.js with the command shown below. In a browser project, configure the Wasm URL to point to the asset your bundler serves. This Node.js check uses the package’s included Wasm file, so the query and export output is reproducible without a browser bundler.
const initSqlJs = require("sql.js");
(async () => {
const SQL = await initSqlJs();
const db = new SQL.Database();
db.run("CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)");
db.run("INSERT INTO notes (body) VALUES (?)", ["draft"]);
console.log(JSON.stringify(db.exec("SELECT id, body FROM notes")));
const bytes = db.export();
console.log(`export bytes: ${bytes.length}`);
const restored = new SQL.Database(bytes);
console.log(JSON.stringify(restored.exec("SELECT count(*) AS n FROM notes")));
db.close();
restored.close();
})();
The query and export returned:
[{"columns":["id","body"],"values":[[1,"draft"]]}]
export bytes: 8192
[{"columns":["n"],"values":[[1]]}]
The last result shows the exported bytes can initialize a second database with the row intact. The byte count is specific to this tiny test database and will vary with its schema and contents.
Step 2: Store the exported database in IndexedDB
IndexedDB stores structured browser data asynchronously. Keep the exported bytes as a value in an object store, then retrieve them before constructing the database. The transaction callbacks below return a promise so the caller can wait for the save or load to finish.
function openStore() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("notes-db", 1);
request.onupgradeneeded = () => {
request.result.createObjectStore("snapshots");
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
async function saveDatabase(db) {
const store = await openStore();
const tx = store.transaction("snapshots", "readwrite");
tx.objectStore("snapshots").put(db.export(), "latest");
await new Promise((resolve, reject) => {
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
tx.onabort = () => reject(tx.error);
});
store.close();
}
Call the save function after a change you want to preserve. To reopen, read the same key from the object store and pass its value to the database constructor. Handle the empty-store case by creating a new database instead.
I use an explicit save boundary here because the successful probe restored the inserted row only after exporting and passing the bytes into a new database. It also makes the cost visible: each save exports a snapshot of the database, rather than only the changed row.
sql.js edge cases: Wasm paths and persistence
A failed WebAssembly request usually means the browser cannot find the matching Wasm asset. Set the locateFile option to the public path used by your build, and check the browser network panel for the requested file and its status.
The official package documentation shows this initialization form for a browser-hosted asset:
const SQL = await initSqlJs({
locateFile: (file) => `/assets/${file}`,
});
Serve the corresponding sql-wasm.wasm file at that path. If the request returns 404, correct the copied asset path rather than changing the database code.
The package contains the wrapper and Wasm files under its distribution directory. Copy both into the assets your browser app publishes, or use a bundler import that emits the Wasm file and returns its final URL. The configured path must match the deployed URL, not only the source-tree location.
I also passed a bound value to a SQL string containing multiple statements and got “column index out of range.” Bind values to one prepared statement or one statement with placeholders, rather than to a multi-statement string. The working insert used one placeholder and a separate value array.
Exporting a large database can take time because sql.js serializes the full database to bytes. A user asked in sql.js issue 302 about saving to IndexedDB without calling export. The discussion distinguishes storing the complete database from persisting only changed rows.
If frequent full exports take too long, measure the database size and save frequency before choosing this design.
IndexedDB writes complete asynchronously, so wait for the transaction to finish before treating a save as durable. Browser storage can also be cleared by a user or constrained by browser policy.
- Save snapshots in IndexedDB for same-browser reloads.
- Offer a file download or server sync when users need another copy.
Conclusion: Treat export as your save boundary
sql.js gives a browser a SQLite database, while the application decides how to retain it. The save boundary is an exported snapshot.
- Export the database after changes.
- Save the bytes in IndexedDB.
- Reload them into a new database when the app starts.
For related approaches, see JavaScript SQLite and SQLite in Node.js. Check the official sql.js API docs for the current API and build files.
FAQ
Does sql.js save data after a browser refresh?
No. Its database is held in memory. Export it and store the returned bytes, for example in IndexedDB, then reopen from those bytes.
Can sql.js open an existing SQLite file?
Yes. Read the file into a Uint8Array and pass it to new SQL.Database(data).
Why does sql.js return a Wasm 404?
The browser cannot find the WebAssembly asset. Set locateFile to the path where your build serves sql-wasm.wasm and verify that URL loads.
