A WebAssembly SQLite driver for Go. It lets Go WASM applications use the standard database/sql API with SQLite running entirely in-process: persisting to OPFS in a browser, and to the host filesystem under Node.
The runtime uses SQLite's supported object-oriented WASM API directly. The deprecated SQLite Worker1/Promiser API is not used at runtime.
Go App (WASM)
-> database/sql driver ("wasmsqlite")
-> syscall/js adapter
-> sqlite-bridge.js RPC client on the main thread
-> sqlite-worker.js dedicated worker
-> sqlite3.oo1.DB / sqlite3.oo1.OpfsDb
-> SQLite WASM + OPFS storage (browser)
-> SQLite WASM + node:fs VFS (Node)
sqlite-worker.js loads sqlite3.js, calls sqlite3InitModule(), and opens databases through the best durable VFS the host offers.
In a browser it imports the script, spawns a Web Worker, and prefers opfs-wl, then opfs-sahpool, then opfs. Under Node it requires the script, spawns a node:worker_threads worker, and uses the nodefs VFS from sqlite-node-vfs.js, which maps SQLite's file operations onto the synchronous node:fs API. SQLite runs in a worker on both hosts, in a browser because OPFS needs worker-side file APIs and under Node so that a busy database cannot stall the host's event loop.
Naming a durable VFS (opfs, opfs-wl, opfs-sahpool, or nodefs) is a promise the worker keeps or breaks loudly. If that VFS cannot be opened, the open fails; it never quietly returns an in-memory database instead. Only vfs=auto may settle for memory, and even then not when require_persistent=true is set. This matters for anything whose database is the only copy of its state, such as a wallet, where silently running against storage that evaporates on exit loses data that cannot be recovered from anywhere else.
Under Node the host must give Go's wasm_exec.js a real filesystem before instantiating the WASM module, and must tell the bridge where the runtime assets live:
globalThis.fs = require("node:fs"); // else wasm_exec.js stubs fs with ENOSYS
globalThis.sqliteBridgeAssetDir = wasmDir; // holds sqlite3.js, sqlite3.wasm, sqlite-worker.js, sqlite-node-vfs.jsTwo Node processes must not write one database. The nodefs VFS enforces that with a pid-stamped lock file taken alongside each main database opened for writing; a lock whose owning process is gone is reclaimed automatically, so a crash does not strand the database. A second process attempting the same database fails to open, and the error names the pid holding it.
The lock file sits next to the database as <database>-nodefs-lock. Deleting it by hand is the recovery if a database is ever stranded behind a lock the VFS declines to reclaim, and is safe exactly when no process is using that database.
Node core exposes neither flock nor fcntl, so this is a lock file rather than a kernel lock, and it is worth knowing where that falls short of the real thing:
- Writers only. A read-only open takes no lock and is not blocked by one. A reader running against a live writer sees confusing errors or stale data rather than silent damage, but it is not excluded.
- One pid namespace, one machine. Two containers sharing a bind-mounted data directory number their processes independently, so each reads the other's lock as belonging to a process that does not exist and both proceed. Over NFS or SMB neither the atomicity nor the pid check holds. Do not point two containers or two hosts at one database directory.
- Recycled pids are handled. The lock records the owner's kernel start time where the platform exposes it (Linux), so a reused pid number does not read as the original owner and strand the database.
- Standard
database/sqldriver namedwasmsqlite - OPFS persistence in supported browsers
- Host filesystem persistence under Node through the
nodefsVFS - In-memory fallback only when no durable VFS was requested
- Transactions through
BEGIN IMMEDIATE,COMMIT, andROLLBACK - BLOB round trips through
[]byte - Database dump/load helpers with BLOB-safe SQL literals
- Embedded SQLite WASM and bridge assets
- Optional
golang-migratedriver support
- Go 1.24+ for this module
- A modern browser with WebAssembly and OPFS support
- HTTPS or localhost for OPFS
- Cross-origin isolation for OPFS support:
Cross-Origin-Opener-Policy: same-originCross-Origin-Embedder-Policy: require-corporcredentialless
The example must be served by a host that sets these headers on the page and runtime assets.
go get github.com/lightninglabs/go-wasmsqliteUse the driver through database/sql:
import (
"database/sql"
_ "github.com/lightninglabs/go-wasmsqlite"
)
func main() {
db, err := sql.Open("wasmsqlite", "file=/myapp.db?vfs=auto&busy_timeout=5000")
if err != nil {
panic(err)
}
defer db.Close()
// Recommended for every OPFS database handle.
db.SetMaxOpenConns(1)
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)`); err != nil {
panic(err)
}
}The convenience helper sets the OPFS connection limit for you:
db, err := wasmsqlite.Open(&wasmsqlite.Options{
File: "/myapp.db",
VFS: "auto",
DisallowMemory: true,
})Direct sql.Open(...) callers should call db.SetMaxOpenConns(1) for each OPFS database. The worker rejects duplicate opens of the same OPFS filename in one worker, and multiple concurrent database handles are not useful for this browser storage model.
Named SQLite parameters are supported through sql.Named:
_, err := db.Exec(
`INSERT INTO notes(id, body) VALUES (:id, $body)`,
sql.Named("id", 1),
sql.Named("body", "hello"),
)Do not mix positional and named parameters in one call.
For high-throughput inserts or updates, use the explicit batch helper. It sends one worker request, prepares the SQL once in the SQLite worker, wraps the whole batch in one transaction, and binds/steps/resets the statement for each row:
result, err := wasmsqlite.ExecBatchContext(ctx, db,
`INSERT INTO notes(id, body) VALUES (?, ?)`,
[][]any{
{1, "hello"},
{2, "world"},
},
)
if err != nil {
panic(err)
}
rows, _ := result.RowsAffected()
fmt.Println(rows)ExecBatchContext is intentionally separate from database/sql prepared
statements. Normal Stmt.Exec calls still execute immediately so per-call
errors, row counts, and read-your-writes behavior remain consistent with
database/sql.
ExecContext, QueryContext, BeginTx, Ping, dump, and load respect context cancellation while waiting for the JavaScript bridge. Canceling a Go context stops waiting on the Go side; it does not forcibly interrupt a SQLite operation that has already been posted to the Worker.
file: database filename, default/app.dbvfs: SQLite VFS, defaultautobusy_timeout: busy timeout in milliseconds, default5000mode: SQLite URI mode such asro,rw,rwc, ormemorycache: SQLite URI cache mode such assharedorprivatejournal_mode: runsPRAGMA journal_mode=<value>after openpragma: semicolon-separated pragmas to run after openworker_url: optional URL forsqlite-worker.jssqlite_js_url: optional URL forsqlite3.js, used bysqlite-worker.jsrequire_persistent: fail instead of falling back to memory when persistent storage is unavailabledisallow_memory: explicit alias forrequire_persistent; fail instead of falling back to memoryparse_time: parse SQLite timestamp strings intotime.Timevalues for scans intotime.Timeorsql.NullTime
parse_time=true recognizes time.RFC3339Nano, time.RFC3339, SQLite-style datetime strings with optional fractional seconds and numeric offsets, YYYY-MM-DD HH:MM:SS, and YYYY-MM-DD.
Supported VFS values:
auto: default; triesopfs-wl, thenopfs-sahpool, thenopfs, then memory if allowedopfs: persistent OPFS database viasqlite3.oo1.OpfsDb; falls back to memory if unavailable and memory is allowedopfs-wl: OPFS database using SQLite's Web Locks VFS for fairer multi-tab lock scheduling when the browser supportsAtomics.waitAsyncopfs-sahpool: explicit SQLite SAH pool VFS when availablememory: in-memory database
file=:memory: also opens an in-memory database.
SQLite WASM assets are embedded with //go:embed. The runtime needs these files to be served from the same directory in a browser app:
sqlite-bridge.jssqlite-worker.jssqlite3.jssqlite3.wasmsqlite3-opfs-async-proxy.js- Go's
wasm_exec.js - your Go WASM binary
The upstream SQLite Worker1 files are intentionally not fetched or published because this project no longer loads them at runtime.
err := wasmsqlite.ExtractAssets("./static/wasm")
if err != nil {
log.Fatal(err)
}ExtractAssets writes the runtime files in a flat layout:
./static/wasm/sqlite-bridge.js
./static/wasm/sqlite-worker.js
./static/wasm/sqlite3.js
./static/wasm/sqlite3.wasm
./static/wasm/sqlite3-opfs-async-proxy.js
handler := wasmsqlite.AssetHandler()
http.Handle("/wasm/", http.StripPrefix("/wasm", handler))Available flat runtime paths include:
/wasm/sqlite3.wasm
/wasm/sqlite3.js
/wasm/sqlite3-opfs-async-proxy.js
/wasm/sqlite-bridge.js
/wasm/sqlite-worker.js
AssetHandler also preserves the embedded /assets/... and /bridge/... paths for direct access, but the flat paths are the browser runtime layout. By default, sqlite-worker.js is resolved relative to the loaded sqlite-bridge.js, and sqlite3.js is resolved relative to sqlite-worker.js. If you serve files from unrelated directories, set both worker_url and sqlite_js_url.
Cross-origin isolation headers must be set on the app page, not only on SQLite assets. Wrap the whole app handler:
app := wasmsqlite.WithCrossOriginIsolation(http.FileServer(http.Dir("./public")))
http.Handle("/", app)A production deployment should serve one flat runtime directory:
public/
index.html
main.wasm
wasm_exec.js
sqlite-bridge.js
sqlite-worker.js
sqlite3.js
sqlite3.wasm
sqlite3-opfs-async-proxy.js
Minimal Go static server:
package main
import (
"log"
"net/http"
"github.com/lightninglabs/go-wasmsqlite"
)
func main() {
app := http.FileServer(http.Dir("./public"))
handler := wasmsqlite.WithCrossOriginIsolation(app)
log.Fatal(http.ListenAndServe(":8080", handler))
}WithCrossOriginIsolation sets COOP/COEP on every response and application/wasm for .wasm files. Static hosts must do the same for the app page. For caching, prefer hash-named immutable files; otherwise deploy main.wasm, sqlite-bridge.js, sqlite-worker.js, sqlite3.js, sqlite3.wasm, and sqlite3-opfs-async-proxy.js together. The bridge and worker include a small protocol check so mismatched runtime files fail clearly instead of producing opaque worker errors.
wasmBytes, _ := wasmsqlite.GetSQLiteWASM()
sqliteJS, _ := wasmsqlite.GetSQLiteJS()
bridgeJS, _ := wasmsqlite.GetBridgeJS()
workerJS, _ := wasmsqlite.GetWorkerJS()Build and serve the demo:
make build-example
make serveThen open http://localhost:8081.
The example uses:
example/index.htmlexample/main.gofor the Go WASM appexample/migrations/withgolang-migrate- generated
database/sqlquery code inexample/generated/
make build-example copies the runtime browser files into example/, which is also what the GitHub Pages workflow publishes.
dump, err := wasmsqlite.DumpDatabase(db)
if err != nil {
return err
}
if err := wasmsqlite.LoadDatabase(db, dump); err != nil {
return err
}Dump output uses hex literals for BLOB values, so []byte data can be restored safely.
storageInfo, err := wasmsqlite.GetStorageInfo(db)
if err != nil {
return err
}
switch storageInfo.VFSType {
case wasmsqlite.VFSTypeOPFS:
// Persistent OPFS storage.
case wasmsqlite.VFSTypeOPFSWebLocks:
// Persistent OPFS storage using SQLite's Web Locks VFS.
case wasmsqlite.VFSTypeOPFSSAHPool:
// Persistent OPFS storage using SQLite's SAH pool VFS.
case wasmsqlite.VFSTypeMemory:
// In-memory storage; data will reset on refresh.
}GetVFSType(conn) remains available when code already has a dedicated *sql.Conn. Use DisallowMemory: true, RequirePersistent: true, disallow_memory=true, or require_persistent=true when falling back to memory would be incorrect.
- One
*sql.DBshould own a given OPFS filename in a page. UseSetMaxOpenConns(1). - Opening the same OPFS filename twice in the same Worker returns
ErrDuplicateOpen. - Opening the same OPFS filename from two tabs uses separate Workers and browser OPFS locking. Browser behavior can differ; apps should handle either a successful second open or an actionable lock/open error.
- Default
vfs=autotriesopfs-wl, thenopfs-sahpool, thenopfs, thenmemoryif fallback is allowed. - Use
vfs=opfs-wlfor multi-tab workloads where Web Locks support is available. It preserves OPFS persistence while letting the browser arbitrate lock acquisition more fairly across tabs. - Use
vfs=opfs-sahpoolfor the explicit SQLite SAH pool VFS when single-tab performance is more important than transparent multi-tab access. - Private/incognito modes may expose reduced or temporary OPFS storage. Use
DisallowMemoryorRequirePersistentwhen data loss would be unacceptable.
The package includes a golang-migrate database driver that runs migrations against an existing *sql.DB:
sourceDriver, err := iofs.New(migrationFS, "migrations")
if err != nil {
return err
}
dbDriver, err := wasmsqlite.NewMigrateDriver(db)
if err != nil {
return err
}
m, err := migrate.NewWithInstance("iofs", sourceDriver, "wasmsqlite", dbDriver)
if err != nil {
return err
}
return m.Up()make setup # Fetch SQLite WASM assets
make build # Fetch assets, build root WASM, and build example
make build-example # Build only the demo app and copy browser runtime files
make serve # Serve demo at http://localhost:8081
make test # Run normal Go tests
make browser-test # Run headless Chrome browser E2E tests
npm test # Run Playwright tests against the built example page
make clean # Remove build artifactsmake fetch-assets reads the official SQLite download metadata and fetches the current sqlite-wasm-*.zip bundle with SHA3 verification. To pin a specific archive, pass SQLITE_URL and EXPECTED_SHA; SQLITE_VERSION=3530100 make fetch-assets selects that version when it is still listed on the download page.
Browser tests build a WASM test binary, serve the SQLite assets with the required headers, launch headless Chrome, and verify OPFS persistence, BLOBs, dump/load, transactions, memory mode, migrations, generated SQL shapes, cancellation, named parameters, browser-context storage behavior, and the example path. CI runs these browser tests on every push and pull request.
The Pages workflow runs make build-example and publishes ./example. The published directory must contain:
index.html_headersmain.wasmwasm_exec.jssqlite-bridge.jssqlite-worker.jssqlite3.jssqlite3.wasmsqlite3-opfs-async-proxy.js
GitHub Pages does not apply _headers, so this workflow is only useful as a static artifact publisher. The public lightning.community route must add the required headers before serving these files.
The public demo is intended to be served from https://lightning.community/go-wasmsqlite/.
The host in front of the built ./example directory must set the OPFS headers
on every response:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Resource-Policy: same-origin
It must also serve *.wasm as application/wasm. The repository keeps
example/_headers for static hosts that understand that file format, but
GitHub Pages does not apply _headers; the lightning.community route should
therefore terminate on a header-capable edge/proxy.
If the route is proxied through Cloudflare, avoid TLS/proxy settings that make
the origin redirect back to the same HTTPS URL. A same-location 301 on
/go-wasmsqlite/ happens before the app loads, so it cannot be fixed by the
demo code.
- SQLite extensions cannot be loaded dynamically.
- OPFS storage is origin-scoped.
- OPFS requires HTTPS or localhost.
- If OPFS is unavailable,
vfs=autoandvfs=opfsfall back to in-memory storage unless memory fallback is disabled. - Context cancellation stops waiting on the Go side but does not interrupt already-running SQLite work in the Worker.
- Named and positional parameters cannot be mixed in the same call.
| Symptom | Likely cause | Fix |
|---|---|---|
ErrBridgeNotLoaded |
sqlite-bridge.js was not loaded before main.wasm |
Load sqlite-bridge.js before starting Go WASM. |
ErrAssetUnavailable |
Worker cannot fetch sqlite3.js, sqlite3.wasm, or the OPFS proxy |
Serve the flat runtime files together or set worker_url and sqlite_js_url. |
ErrPersistentRequired |
RequirePersistent or DisallowMemory was set but OPFS/persistent storage is unavailable |
Show a user-facing persistence error or allow memory fallback for demo mode. |
ErrDuplicateOpen |
Same OPFS filename opened twice in one Worker | Use one *sql.DB per OPFS file and SetMaxOpenConns(1). |
ErrUnsupportedVFS |
Requested VFS is not available in the browser build | Use auto, opfs, opfs-wl, opfs-sahpool, or memory. |
ErrNamedParameter |
Mixed positional/named params, missing named param, or unused named param | Use all positional or all named params and match SQL names. |
ErrProtocolMismatch |
Cached runtime JS files are from different versions | Redeploy sqlite-bridge.js, sqlite-worker.js, SQLite assets, and main.wasm together. |
| Component | Current support |
|---|---|
| Go | 1.24+ |
| SQLite WASM | Official sqlite-wasm bundle, currently 3.53.1 / 3530100 |
| Browser | Modern Chromium-class browsers with WebAssembly; OPFS requires secure context and cross-origin isolation |
| VFS modes | auto, opfs-wl, opfs-sahpool, opfs, memory |
| SQL API | Go database/sql, positional and named parameters, transactions, BLOBs, parse_time, dump/load |
| Unsupported | Dynamic SQLite extensions, forced interruption of already-running Worker SQL |
Releases should follow semantic versioning. Runtime JS/WASM files are part of the compatibility contract and should be deployed with the matching Go module version.
MIT
- SQLite for SQLite and the official WASM build
- database/sql for the standard Go SQL API