
PGlite: Put a Real Postgres Database Inside a Browser Tab
Build an offline CSV explorer with PGlite, browser-persisted Postgres, SQL charts and transactional imports. Test query results, reloads and offline recovery.
PGlite runs PostgreSQL compiled to WebAssembly inside your application, including a browser tab. You can create tables, enforce constraints, join records and commit transactions without operating a database server. With its IndexedDB filesystem, the database can outlive the page that opened it. PGlite documentation.
I used it to build an expenses CSV explorer with SQL queries and a reactive chart. The fixture returned the expected 7 rows and €67.00. After the application was cached, a replacement import worked offline, survived a new-document reload and could be restored from an exported CSV.
The useful surprise was a limit: a configured PostgreSQL statement timeout did not interrupt a deliberately slow query in our Node/PGlite check. This browser example runs its database on the main thread, so expensive SQL can still freeze the interface. Below are the working initialization, schema, transaction and live query, followed by the recovery checks and complete download.
What changes when browser storage can answer SQL
The draft-recovery guide asks which copy of a document was successfully saved and how a returning page should reconcile it. Here the next question is relational: which records belong together, what rules must every row satisfy, and can an import become visible as one complete change?
For a handful of settings, a key/value store is enough. For expenses grouped by category, daily totals, comparisons between months or a join against a budget table, SQL becomes a useful interface. PGlite supplies PostgreSQL’s query semantics and transactions through a JavaScript client. It uses PostgreSQL’s single-user capabilities; this is an embedded database with a single connection. It does not give each browser visitor a connection to a shared remote service. Pinned architecture and limitations.
Why choose PGlite for this experiment? I wanted to use PostgreSQL’s types, constraints and transaction behavior together with PGlite’s live-query integration in a browser. That combination is useful when PostgreSQL-oriented schemas and queries are already familiar or part of an application’s design. A seven-row ledger alone does not require Postgres: SQLite WASM and DuckDB-Wasm also support browser SQL. This experiment tests embedded Postgres; it does not rank those alternatives.
There is still an application to distribute: HTML, JavaScript, CSS and the WebAssembly runtime. A static host can serve those files. After they have been cached successfully, this explorer’s import and query workflow needs no database service.
Build a bounded expenses explorer
The download accepts this header:
spent_on,category,amount_cents,note
Dates are calendar dates, amounts are integer cents and categories are ordinary text. The lab treats amounts as EUR cents; it does not combine currencies or infer exchange rates. Integer cents avoid introducing binary floating-point arithmetic into the fixture’s money totals.
The seven-row synthetic fixture has these known answers. On narrow screens, focus a table region to scroll it horizontally.
| Category | Rows | Total cents |
|---|---|---|
| Food | 3 | 2500 |
| Transport | 2 | 1200 |
| Tools | 2 | 3000 |
| All expenses | 7 | 6700 |
The application displays a category chart and a SQL result table. Imports replace the current dataset deliberately; they do not silently append the same file twice. Export the current data before replacing something you want to retain.
Persist the database, then define its rules
new PGlite() creates an in-memory database. Selecting an idb:// data directory enables IndexedDB persistence. The live-query extension is registered when the instance is created. Getting started, live-query setup.
These are the imports and initialization from app.mjs. The initialization runs after the page acquires the database’s tab lock:
import { PGlite } from '@electric-sql/pglite';
import { live } from '@electric-sql/pglite/live';
import { initSchema } from './core.mjs';
let database;
database = await PGlite.create('idb://criticaldeveloper-expenses-v1', { extensions: { live } });
await initSchema(database);
The stable database name lets the next document reopen the same data. Normal durability is the default here: the code does not enable relaxedDurability, which can return before filesystem flushing finishes. The IndexedDB backend loads database files into memory and writes changed files back to storage. Filesystem behavior, API options.
The schema uses PostgreSQL types and constraints. A DATE stores the expense’s calendar day. A nonnegative integer amount and bounded text lengths prevent a malformed row from quietly becoming part of the dataset. Schema creation is startup work; importing another CSV does not recreate the database.
Here is initSchema() from core.mjs:
export async function initSchema(db) {
await db.exec(`CREATE TABLE IF NOT EXISTS expenses (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
spent_on date NOT NULL,
category text NOT NULL CHECK (length(trim(category)) > 0 AND length(category) <= 80),
amount_cents integer NOT NULL CHECK (amount_cents BETWEEN 0 AND 100000000),
note text NOT NULL CHECK (length(note) <= 500)
)`);
await db.syncToFs();
}
For a larger application, version those schema changes and plan migrations. Reusing the database name does not make a changed schema compatible with old records.
Make the import one transaction
CSV parsing deserves more than split(','). Quoted commas, escaped quotes, CRLF and embedded line breaks can all occur in a valid file. The lab parses that structure, validates the header and fields, and bounds input size before writing records.
Once parsing and validation succeed, replaceExpenses() in core.mjs replaces the dataset:
export async function replaceExpenses(db, rows) {
await db.transaction(async (tx) => {
await tx.query('DELETE FROM expenses');
for (const row of rows) {
await tx.query(`INSERT INTO expenses (spent_on, category, amount_cents, note)
VALUES ($1, $2, $3, $4)`, [row.spent_on, row.category, row.amount_cents, row.note]);
}
});
// Successful COMMIT and successful filesystem synchronization are separate steps.
try { await db.syncToFs(); }
catch (cause) {
throw new Error('Rows committed, but final local persistence could not be confirmed. Export a backup before closing.', { cause });
}
return rows.length;
}
If a database constraint rejects a later row, the transaction rolls back the earlier inserts and the deletion. The old dataset remains available. This is the useful difference between an atomic import and a loop that leaves half a file behind. PGlite commits when its transaction callback resolves and rolls back when it rejects. Transaction API.
The $1–$4 parameters carry values separately from the SQL text, including category and note text. For this small importer, one insert per row makes the validation and failure path easy to inspect. PGlite also supports PostgreSQL COPY through a Blob for bulk imports. Query parameters and Blob input.
The function returns a row count only after the transaction and final filesystem synchronization succeed; that is when the UI reports saved locally. A rejected transaction leaves the old dataset intact. A rejected flush after commit is a different error: the in-memory ledger may already have changed, so the message preserves that uncertainty and directs the user to export it.
Ask a question with a known answer
Run this query after loading the fixture:
SELECT category,
count(*)::integer AS rows,
sum(amount_cents)::float8 AS total_cents
FROM expenses
GROUP BY category
ORDER BY category;
It should return Food/3/2500, Tools/2/3000 and Transport/2/1200, in that order. SQL orders the result explicitly; the chart can choose its own visual ordering.
Check the whole dataset independently:
SELECT count(*)::integer AS rows,
sum(amount_cents)::float8 AS total_cents
FROM expenses;
The expected result is one row containing 7 and 6700. The aggregate uses float8 to return a JavaScript number without narrowing PostgreSQL’s sum to a 32-bit integer. Within this lab’s limits, at most 10,000 rows of 100,000,000 cents total 10¹² cents, which remains an exactly representable integer.
The SQL editor runs exploratory queries inside a read-only transaction and displays at most 200 rows. Database-enforced read-only mode is a stronger rule than accepting any text that starts with SELECT. The tool remains a local workbench, and a user who controls the page can change its code.
A result limit is not a computation limit. During the pinned runtime check, setting statement_timeout to 1500 milliseconds did not interrupt SELECT pg_sleep(2). The delivered lab therefore makes no timeout guarantee. Aggregates, sorts and expensive functions can still occupy the main thread even when the final result is small. Imports are capped at 2 MiB and 10,000 rows; a production SQL workbench needs worker execution and a tested cancellation/recovery design.
Let a live query update the chart
The chart uses this aggregate from core.mjs, subscribed in app.mjs:
export const CATEGORY_TOTALS_SQL = `
SELECT category, sum(amount_cents)::float8 AS total_cents,
count(*)::int AS entries
FROM expenses GROUP BY category ORDER BY total_cents DESC, category
`;
let subscription;
subscription = await database.live.query(CATEGORY_TOTALS_SQL, [], result => drawChart(result.rows));
PGlite’s live extension tracks the tables the query depends on and reruns it when they change. The callback passes those rows to drawChart(), which updates the bars and total using DOM text nodes. SQL supplies the aggregation rules; rendering supplies the presentation. Live-query behavior and API.
The standalone lab keeps this subscription for the owning document’s lifetime. It does not run a component teardown handler. If you move the chart into a component that can unmount while the database stays open, call await subscription.unsubscribe() during teardown so it stops receiving updates.
“Reactive” describes this database-to-view relationship. It does not mean another laptop receives the changes. Cross-device synchronization needs an explicit protocol and, usually, another service.
Keep database ownership explicit across tabs too. PGlite documents a multi-tab worker that shares one instance through an elected leader. This lab instead admits one cooperating owner tab using Web Locks and gives a second tab a visible blocked state. It does not open two independent writers against the same stored database. Multi-tab worker, Web Locks.
Offline requires the program and the database
Two independent stores make the offline path work:
| Store | Contents | What it enables |
|---|---|---|
| IndexedDB | PostgreSQL data files | Reopen previously imported records |
| Service-worker cache | HTML, CSS, JavaScript and runtime assets | Load the application without the network |
Saving the database alone cannot repair a missing JavaScript bundle. Leaving a tab open while disconnected also says nothing about whether a fresh document can initialize offline.
The production lab bundles its dependencies locally and precaches its generated files, including pglite.wasm, initdb.wasm and pglite.data. It reports offline readiness only after that cache preparation succeeds. Runtime CDN imports would add another dependency to this test. PGlite’s bundler guide documents the asset handling and Vite configuration. Bundler support.
That convenience has a download cost. This pinned production build emits 17,475,049 bytes (16.67 MiB) across 11 files, dominated by the main WASM module and PostgreSQL data bundle. That is the uncompressed size of files on disk; compressed transfer, startup time and memory use need their own measurements.
Service workers require a secure context; localhost is allowed for development. Build and serve the production output for the offline check. The development server is not the production cache contract. Service-worker requirements.
Run the companion lab
Download the complete source ZIP and follow the README. Use synthetic records on a dedicated local origin. Installing dependencies and building initially need network access; the offline claim concerns the prepared application.
With Node.js 22.12 or later and Bun installed, extract the ZIP and run these commands in its directory:
bun install --frozen-lockfile
bun run test
bun run build
bun run start
Open http://127.0.0.1:4387/, load the sample and wait for Offline shell ready. The tested versions are Node.js 24.22.1, Bun 1.4.4, PGlite 0.5.11 and Vite 8.3.5. PGlite 0.5.11 was released on October 21, 2026; its persistence and live-query support were already available before that patch. 0.5.11 release, previous live-query documentation.
Keep the same hostname, port and browser profile for the reload test. localhost and 127.0.0.1, or different ports, identify different origins and therefore different storage. A localhost demo’s path is not an isolation boundary from other applications on that origin. Browser storage policy.
The source viewer contains the actual downloadable implementation:
Source files
7 filescore.mjs
CSV validation, schema and transactional imports
export const MAX_BYTES = 2 * 1024 * 1024;
export const MAX_ROWS = 10_000;
const HEADER = ['spent_on', 'category', 'amount_cents', 'note'];
export const CATEGORY_TOTALS_SQL = `
SELECT category, sum(amount_cents)::float8 AS total_cents,
count(*)::int AS entries
FROM expenses GROUP BY category ORDER BY total_cents DESC, category
`;
function csvRecords(text) {
const records = [];
let row = [], field = '', quoted = false, closed = false;
let started = false;
function pushField() { row.push(field); field = ''; closed = false; }
function pushRow() {
pushField();
records.push(row);
if (records.length > MAX_ROWS + 1) throw new Error(`CSV exceeds ${MAX_ROWS} data rows.`);
row = []; started = false;
}
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (quoted) {
if (char === '"') {
if (text[i + 1] === '"') { field += '"'; i++; }
else { quoted = false; closed = true; }
} else field += char;
continue;
}
if (char === ',') { pushField(); started = true; continue; }
if (char === '\n' || char === '\r') {
if (char === '\r') {
if (text[i + 1] !== '\n') throw new Error('Use LF or CRLF line endings.');
i++;
}
pushRow(); continue;
}
if (closed) throw new Error('Unexpected character after a closing CSV quote.');
if (char === '"') {
if (field.length) throw new Error('A CSV quote must start a field.');
quoted = true; started = true;
} else { field += char; started = true; }
}
if (quoted) throw new Error('Unclosed CSV quote.');
if (started || row.length || field.length || closed) pushRow();
return records;
}
export function parseExpenses(text) {
if (typeof text !== 'string') throw new Error('CSV must be text.');
if (new TextEncoder().encode(text).byteLength > MAX_BYTES) throw new Error('CSV exceeds 2 MiB.');
const records = csvRecords(text.replace(/^\uFEFF/, ''));
const header = records.shift();
if (!header || header.length !== HEADER.length || header.some((value, i) => value !== HEADER[i])) {
throw new Error(`Expected header: ${HEADER.join(',')}`);
}
return records.map((values, index) => {
const fail = (message) => { throw new Error(`Data row ${index + 1}: ${message}`); };
if (values.length !== 4) fail('expected four columns.');
const [spent_on, category, cents, note] = values;
const date = /^\d{4}-\d{2}-\d{2}$/.test(spent_on) && spent_on.slice(0, 4) !== '0000'
? new Date(`${spent_on}T00:00:00.000Z`) : null;
if (!date || Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== spent_on) {
fail('spent_on must be a real YYYY-MM-DD date.');
}
if (!category.trim() || category.length > 80 || category.includes('\0')) {
fail('category must contain 1–80 characters and no NUL.');
}
if (!/^\d+$/.test(cents) || !Number.isSafeInteger(Number(cents)) || Number(cents) > 100_000_000) {
fail('amount_cents must be an integer from 0 to 100000000.');
}
if (note.length > 500 || note.includes('\0')) fail('note must contain at most 500 characters and no NUL.');
return { spent_on, category, amount_cents: Number(cents), note };
});
}
export function expensesCsv(rows) {
const quote = (value) => `"${String(value).replaceAll('"', '""')}"`;
return HEADER.join(',') + '\r\n' + rows.map((row) => HEADER.map((key) => quote(row[key])).join(',')).join('\r\n') + (rows.length ? '\r\n' : '');
}
export async function initSchema(db) {
await db.exec(`CREATE TABLE IF NOT EXISTS expenses (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
spent_on date NOT NULL,
category text NOT NULL CHECK (length(trim(category)) > 0 AND length(category) <= 80),
amount_cents integer NOT NULL CHECK (amount_cents BETWEEN 0 AND 100000000),
note text NOT NULL CHECK (length(note) <= 500)
)`);
await db.syncToFs();
}
// Call with validated rows. The database constraints still protect each insert.
export async function replaceExpenses(db, rows) {
await db.transaction(async (tx) => {
await tx.query('DELETE FROM expenses');
for (const row of rows) {
await tx.query(`INSERT INTO expenses (spent_on, category, amount_cents, note)
VALUES ($1, $2, $3, $4)`, [row.spent_on, row.category, row.amount_cents, row.note]);
}
});
// Successful COMMIT and successful filesystem synchronization are separate steps.
try { await db.syncToFs(); }
catch (cause) {
throw new Error('Rows committed, but final local persistence could not be confirmed. Export a backup before closing.', { cause });
}
return rows.length;
}
export async function importExpenses(db, text) {
return replaceExpenses(db, parseExpenses(text));
}
query.mjs
Read-only SQL adapter and result bound
export async function queryLedger(db, sql) {
if (typeof sql !== 'string' || !sql.trim() || sql.length > 10000) {
throw new Error('Enter a SELECT query of up to 10,000 characters.');
}
const statement = sql.trim().replace(/;\s*$/, '');
return db.transaction(async tx => {
await tx.exec('SET TRANSACTION READ ONLY');
return tx.query(`SELECT * FROM (${statement}) AS explorer_result LIMIT 201`);
});
}
app.mjs
Database ownership, live chart and SQL interface
import { PGlite } from '@electric-sql/pglite';
import { live } from '@electric-sql/pglite/live';
import sample from './expenses.csv?raw';
import { MAX_BYTES, initSchema, importExpenses, expensesCsv, CATEGORY_TOTALS_SQL } from './core.mjs';
import { queryLedger } from './query.mjs';
const element = id => document.getElementById(id);
const bootId = crypto.randomUUID();
document.body.dataset.bootId = bootId;
element('environment').textContent = `PGlite 0.5.11 · IndexedDB · document ${bootId}`;
const money = cents => new Intl.NumberFormat('en-IE', { style: 'currency', currency: 'EUR' }).format(Number(cents) / 100);
let db;
let busy = false;
let subscription;
function report(id, message, error = false) {
const target = element(id);
target.textContent = message;
target.classList.toggle('error', error);
}
function controls() {
for (const id of ['sample', 'file', 'run']) element(id).disabled = !db || busy;
element('export').disabled = !db || busy;
}
async function operation(id, action) {
if (!db || busy) return;
busy = true;
controls();
try { await action(); }
catch (error) { report(id, error instanceof Error ? error.message : String(error), true); }
finally { busy = false; controls(); }
}
function drawChart(rows) {
const chart = element('chart');
chart.replaceChildren();
if (!rows.length) {
const text = document.createElement('p');
text.textContent = 'No rows yet. Load the sample or import a CSV.';
chart.append(text);
}
const largest = Math.max(1, ...rows.map(row => Number(row.total_cents)));
let total = 0;
for (const row of rows) {
total += Number(row.total_cents);
const line = document.createElement('div'); line.className = 'bar-row';
const label = document.createElement('span'); label.className = 'bar-label'; label.textContent = row.category;
const track = document.createElement('div'); track.className = 'bar-track'; track.setAttribute('aria-hidden', 'true');
const bar = document.createElement('div'); bar.className = 'bar-fill'; bar.style.width = `${Number(row.total_cents) / largest * 100}%`;
const value = document.createElement('span'); value.className = 'bar-value'; value.textContent = money(row.total_cents);
track.append(bar); line.append(label, track, value); chart.append(line);
}
element('ledger-total').textContent = money(total);
chart.dataset.updates = String(Number(chart.dataset.updates || 0) + 1);
}
function drawResult(result) {
const region = element('result'); region.replaceChildren();
const table = document.createElement('table');
const head = document.createElement('thead'); const heading = document.createElement('tr');
for (const field of result.fields) { const th = document.createElement('th'); th.scope = 'col'; th.textContent = field.name; heading.append(th); }
head.append(heading); table.append(head);
const body = document.createElement('tbody');
for (const row of result.rows.slice(0, 200)) {
const tr = document.createElement('tr');
for (const field of result.fields) {
const td = document.createElement('td'); const value = row[field.name];
td.textContent = value === null ? 'NULL' : typeof value === 'object' ? JSON.stringify(value) : String(value);
tr.append(td);
}
body.append(tr);
}
table.append(body); region.append(table);
report('query-status', result.rows.length > 200 ? 'Showing the first 200 rows. Add filters or a smaller LIMIT.' : `${result.rows.length} result row(s).`);
}
async function importText(text) {
report('import-status', 'Replacing the ledger in one transaction…');
const count = await importExpenses(db, text);
report('import-status', `${count} rows saved locally. Export a CSV for a separate backup.`);
// A query error does not change the outcome of the completed import.
try { drawResult(await queryLedger(db, element('sql').value)); }
catch (error) { element('result').replaceChildren(); report('query-status', error.message, true); }
}
element('sample').addEventListener('click', () => operation('import-status', () => importText(sample)));
element('file').addEventListener('change', () => operation('import-status', async () => {
const file = element('file').files[0]; if (!file) return;
if (file.size > MAX_BYTES) throw new Error('CSV exceeds the 2 MiB limit.');
try { await importText(await file.text()); }
finally { element('file').value = ''; }
}));
element('run').addEventListener('click', () => operation('query-status', async () => {
report('query-status', 'Running query…');
try { drawResult(await queryLedger(db, element('sql').value)); }
catch (error) { element('result').replaceChildren(); throw error; }
}));
element('export').addEventListener('click', () => operation('import-status', async () => {
const result = await db.query("SELECT to_char(spent_on, 'YYYY-MM-DD') AS spent_on, category, amount_cents, note FROM expenses ORDER BY id");
const blob = new Blob([expensesCsv(result.rows)], { type: 'text/csv;charset=utf-8' });
const url = URL.createObjectURL(blob); const link = document.createElement('a');
link.href = url; link.download = 'expenses-backup.csv'; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
report('import-status', 'CSV download requested. Verify the downloaded file before relying on it.');
}));
async function offlineReady() {
if (!('serviceWorker' in navigator)) throw new Error('Service workers unavailable; offline reload is not ready.');
await navigator.serviceWorker.register('./sw.js');
await navigator.serviceWorker.ready;
if (!navigator.serviceWorker.controller) await new Promise(resolve => navigator.serviceWorker.addEventListener('controllerchange', resolve, { once: true }));
const state = await new Promise((resolve, reject) => {
const channel = new MessageChannel();
const timeout = setTimeout(() => reject(new Error('Offline cache check timed out. Reload online to retry.')), 30000);
channel.port1.onmessage = event => { clearTimeout(timeout); resolve(event.data); };
navigator.serviceWorker.controller.postMessage('CHECK_OFFLINE', [channel.port2]);
});
if (!state.ready) throw new Error('Offline cache is incomplete. Reload online to retry.');
report('offline-status', `Offline shell ready · ${state.files} cached files`);
document.body.dataset.offlineReady = 'true';
}
offlineReady().catch(error => report('offline-status', error.message, true));
async function ownDatabase() {
if (!navigator.locks) { report('database-status', 'Web Locks unavailable. Use a browser with Web Locks to protect this one-tab database.', true); return; }
report('database-status', 'Waiting for database ownership. Close any other lab tab.');
await navigator.locks.request('criticaldeveloper-pglite-expenses-v1', async () => {
let database;
try {
report('database-status', 'Opening local Postgres…');
database = await PGlite.create('idb://criticaldeveloper-expenses-v1', { extensions: { live } });
await initSchema(database);
subscription = await database.live.query(CATEGORY_TOTALS_SQL, [], result => drawChart(result.rows));
db = database;
report('database-status', 'Postgres ready · saved in IndexedDB');
document.body.dataset.databaseReady = 'true';
controls();
try { drawResult(await queryLedger(db, element('sql').value)); }
catch (error) { report('query-status', error.message, true); }
// The document holds ownership; the browser releases its lock on destruction.
await new Promise(() => {});
} catch (error) {
db = undefined;
document.body.dataset.databaseReady = 'false';
controls();
if (database) await database.close().catch(() => {});
report('database-status', `Database unavailable: ${error.message}`, true);
}
});
}
ownDatabase().catch(error => report('database-status', error.message, true));
build-offline.mjs
Complete asset inventory and service-worker generation
import { readdir, readFile, writeFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { Script } from 'node:vm';
const root = new URL('./dist/', import.meta.url);
async function inventory(dir, prefix = '') {
const result = [];
for (const entry of await readdir(dir, { withFileTypes: true })) {
const name = `${prefix}${entry.name}`;
if (entry.isDirectory()) result.push(...await inventory(new URL(`${entry.name}/`, dir), `${name}/`));
else result.push(name);
}
return result.sort();
}
const files = await inventory(root);
const hash = createHash('sha256');
for (const file of files) hash.update(file).update(await readFile(new URL(file, root)));
const revision = hash.digest('hex').slice(0, 16);
const script = `const CACHE='pglite-csv-${revision}';
const FILES=${JSON.stringify(['./', ...files.map(file => `./${file}`)])};
self.addEventListener('install',event=>event.waitUntil((async()=>{
const cache=await caches.open(CACHE);
await cache.addAll(FILES);
await self.skipWaiting();
})()));
self.addEventListener('activate',event=>event.waitUntil((async()=>{
for(const name of await caches.keys()) if(name.startsWith('pglite-csv-')&&name!==CACHE) await caches.delete(name);
await self.clients.claim();
})()));
self.addEventListener('fetch',event=>{
if(event.request.method!=='GET'||new URL(event.request.url).origin!==self.location.origin)return;
event.respondWith((async()=>{
const hit=await caches.match(event.request,{cacheName:CACHE});
return hit||fetch(event.request);
})());
});
self.addEventListener('message',event=>{
if(event.data!=='CHECK_OFFLINE')return;
event.waitUntil((async()=>{
const cache=await caches.open(CACHE);
const hits=await Promise.all(FILES.map(file=>cache.match(new URL(file,self.location.href))));
const ready=hits.every(Boolean);
event.ports[0]?.postMessage({ready,revision:CACHE,files:FILES.length});
})());
});
`;
new Script(script, { filename: 'sw.js' });
await writeFile(new URL('sw.js', root), script);
console.log(`Offline shell ${revision}: ${files.length + 1} cached URLs (including WebAssembly/data assets).`);
core.test.mjs
CSV, database rollback and flush-failure checks
import test from 'node:test';
import assert from 'node:assert/strict';
import { PGlite } from '@electric-sql/pglite';
import { MAX_BYTES, MAX_ROWS, parseExpenses, expensesCsv, initSchema, importExpenses, replaceExpenses, CATEGORY_TOTALS_SQL } from './core.mjs';
const header = 'spent_on,category,amount_cents,note';
const example = `${header}\r\n2026-10-01,Food,1250,"Lunch, tea"\r\n2026-10-02,Travel,750,"A ""quoted"" ticket"\r\n`;
test('CSV understands quoted commas, escaped quotes, CRLF, BOM and embedded newline', () => {
const rows = parseExpenses('\uFEFF' + example + '2026-10-03,Food,100,"line one\nline two"\r\n');
assert.equal(rows.length, 3);
assert.equal(rows[0].note, 'Lunch, tea');
assert.equal(rows[1].note, 'A "quoted" ticket');
assert.equal(rows[2].note, 'line one\nline two');
});
test('CSV export and import preserve values including HTML-looking text', () => {
const rows = parseExpenses(`${header}\n2024-02-29,"<img src=x onerror=alert(1)>",0,"=SUM(1,2)"\n`);
assert.deepEqual(parseExpenses(expensesCsv(rows)), rows);
assert.deepEqual(parseExpenses(expensesCsv([])), []);
});
test('CSV rejects malformed syntax and wrong headers or column counts', () => {
for (const csv of ['', `${header}\n2026-10-01,Food,1,"open`, `${header}\n2026-10-01,Food,1,has"quote`, `${header}\n2026-10-01,Food,1,"closed"extra`, `${header}\n2026-10-01,Food,1`, `${header}\n\n`, `${header}\r2026-10-01,Food,1,note`, 'note,category,amount_cents,spent_on']) {
assert.throws(() => parseExpenses(csv));
}
});
test('CSV rejects invalid dates, money, missing categories and oversized fields', () => {
for (const row of ['2026-02-29,Food,1,note', '0000-01-01,Food,1,note', '2026-13-01,Food,1,note', '2026-10-01, ,1,note', '2026-10-01,Food,-1,note', '2026-10-01,Food,1.5,note', '2026-10-01,Food,1e3,note', '2026-10-01,Food,100000001,note', `2026-10-01,${'x'.repeat(81)},1,note`, `2026-10-01,Food,1,${'x'.repeat(501)}`, '2026-10-01,Food,1,nul\0text']) {
assert.throws(() => parseExpenses(`${header}\n${row}\n`));
}
});
test('CSV enforces byte and row limits', () => {
assert.throws(() => parseExpenses('x'.repeat(MAX_BYTES + 1)), /2 MiB/);
assert.throws(() => parseExpenses(`${header}\n` + '2026-10-01,Food,1,note\n'.repeat(MAX_ROWS + 1)), /data rows/);
});
test('actual Postgres aggregates deterministic values and rolls back a failed replacement', async () => {
const db = new PGlite();
try {
await initSchema(db);
assert.equal(await importExpenses(db, example), 2);
assert.deepEqual((await db.query(CATEGORY_TOTALS_SQL)).rows, [
{ category: 'Food', total_cents: 1250, entries: 1 },
{ category: 'Travel', total_cents: 750, entries: 1 },
]);
const before = (await db.query('SELECT category, amount_cents FROM expenses ORDER BY id')).rows;
await assert.rejects(() => replaceExpenses(db, [
{ spent_on: '2026-10-03', category: 'Valid first insert', amount_cents: 100, note: '' },
{ spent_on: '2026-10-03', category: 'Invalid second insert', amount_cents: -1, note: '' },
]), /check constraint/);
assert.deepEqual((await db.query('SELECT category, amount_cents FROM expenses ORDER BY id')).rows, before);
await assert.rejects(() => importExpenses(db, `${header}\n2026-02-29,Food,1,note\n`), /real YYYY-MM-DD/);
assert.deepEqual((await db.query('SELECT category, amount_cents FROM expenses ORDER BY id')).rows, before);
const exported = await db.query("SELECT to_char(spent_on, 'YYYY-MM-DD') AS spent_on, category, amount_cents, note FROM expenses ORDER BY id");
assert.equal(await importExpenses(db, expensesCsv(exported.rows)), 2);
assert.deepEqual((await db.query('SELECT category, amount_cents FROM expenses ORDER BY id')).rows, before);
const failFinalSync = {
transaction: db.transaction.bind(db),
syncToFs: async () => { throw new Error('injected final synchronization failure'); },
};
await assert.rejects(() => importExpenses(failFinalSync, `${header}\n2026-10-03,After commit,100,note\n`), /final local persistence could not be confirmed/);
assert.deepEqual((await db.query('SELECT category, amount_cents FROM expenses')).rows,
[{ category: 'After commit', amount_cents: 100 }]);
} finally { await db.close(); }
});
query.test.mjs
Exact article SQL and database read-only checks
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { PGlite } from '@electric-sql/pglite';
import { initSchema, importExpenses } from './core.mjs';
import { queryLedger } from './query.mjs';
test('article SQL, read-only failures, row bound and subsequent recovery use actual Postgres', async () => {
const db = new PGlite();
try {
await initSchema(db);
await importExpenses(db, await readFile(new URL('./expenses.csv', import.meta.url), 'utf8'));
assert.deepEqual((await db.query('SELECT category, count(*)::integer AS rows, sum(amount_cents)::float8 AS total_cents FROM expenses GROUP BY category ORDER BY category;')).rows, [
{ category: 'Food', rows: 3, total_cents: 2500 },
{ category: 'Tools', rows: 2, total_cents: 3000 },
{ category: 'Transport', rows: 2, total_cents: 1200 },
]);
assert.deepEqual((await db.query('SELECT count(*)::integer AS rows,sum(amount_cents)::float8 AS total_cents FROM expenses;')).rows, [{ rows: 7, total_cents: 6700 }]);
await assert.rejects(() => queryLedger(db, 'DELETE FROM expenses'), /syntax error/);
await assert.rejects(() => queryLedger(db, 'WITH erased AS (DELETE FROM expenses RETURNING *) SELECT * FROM erased'), /top level/);
await assert.rejects(() => queryLedger(db, "SELECT nextval(pg_get_serial_sequence('expenses','id'))"), /read.only transaction/);
assert.equal((await queryLedger(db, 'SELECT * FROM generate_series(1, 300)')).rows.length, 201);
assert.deepEqual((await queryLedger(db, 'SELECT count(*)::int AS rows FROM expenses;')).rows, [{ rows: 7 }]);
await db.query('INSERT INTO expenses(spent_on,category,amount_cents,note) SELECT $1,$2,100000000,$3 FROM generate_series(1,22)', ['2026-10-05', 'Large valid values', 'synthetic']);
assert.equal((await queryLedger(db, 'SELECT SUM(amount_cents)::float8 AS total_cents FROM expenses')).rows[0].total_cents, 2200006700);
} finally { await db.close(); }
});
README.md
Setup, offline checks and recovery limits
# PGlite offline CSV explorer
An independent browser lab for Critical Developer. It runs PGlite 0.5.11, with
Vite 8.3.5 used only to build the files. The blog itself does not depend on either.
Use synthetic data on a dedicated local origin.
## Run
Install Node.js 22.12+ (tested with 24.22.1) and Bun (tested with 1.4.4). Extract
the complete ZIP into a directory, open a terminal there, then run:
```sh
bun install --frozen-lockfile
bun run test
bun run build
bun run start
```
Open <http://127.0.0.1:4387/>. The server binds only to loopback and serves only
the built files. Use the production build, not a Vite development server, for the
offline experiment. Installation and the initial build need internet access.
The build creates a `dist/` folder with bundled JavaScript, CSS, both WebAssembly
modules, and PGlite's data bundle. No runtime CDN is used. `sw.js` is generated
from the actual build file inventory and checked for syntax before it is saved.
The cache includes all emitted assets, including initdb for creating a new database.
Do not open `index.html` using `file:`. This lab needs a secure context such as
HTTP loopback or HTTPS, IndexedDB, service workers and Web Locks. Only one tab
owns this database. A second lab tab waits, with controls disabled, until the
first document closes. The lock coordinates this app; it is not a security boundary.
## Three separate checks
1. **Known results.** Click **Load synthetic sample**. There are seven rows:
Food = 2,500 cents (3 purchases), Tools = 3,000 (2), Transport = 1,200 (2).
The total is 6,700 cents (€67.00). Enter this exact query and run it:
```sql
SELECT category, count(*)::integer AS rows,
sum(amount_cents)::float8 AS total_cents
FROM expenses
GROUP BY category
ORDER BY category;
```
2. **Reload persistence.** Record the document ID in the footer. Reload at the
same URL using the same browser profile. The ID changes, while the chart and
SQL results retain seven rows and 6,700 cents. `localhost`, `127.0.0.1` and
different ports are different origins. Stopping the server does not clear
IndexedDB, but clearing browser storage does.
3. **Offline operation and reload.** Wait for **Offline shell ready** and for
the database to finish loading. Set the browser's network to Offline in
developer tools, or disconnect the external network. Query again, choose a
local CSV, and check that the reactive chart changes. Reload while still
offline: the service worker supplies the application files, and IndexedDB
supplies the database. This requires a previously completed offline cache;
a first-ever offline visit cannot install the application.
The automated published run uses Playwright's browser-context offline setting,
which leaves service workers enabled. It does not prove a physical network
adapter was disconnected or establish compatibility across browsers/devices.
## Import, export and recovery
The CSV format is exactly `spent_on,category,amount_cents,note`, in that order.
Import accepts LF or CRLF, UTF-8 BOM, quoted commas/newlines and doubled quotes.
Dates must be actual ISO calendar dates (`YYYY-MM-DD`, years 0001–9999). Category
is required and limited to 80 UTF-16 code units; note is limited to 500.
Amounts are integer cents from 0 to 100,000,000. The file is limited to 2 MiB
and 10,000 data rows. This schema is for expenses, not a generic CSV schema
inference engine. All fixture rows are synthetic EUR values.
An import replaces all current rows. The entire file is parsed and validated
before the replacement transaction. Bound parameters carry values into SQL;
Postgres constraints remain the final guard. A constraint failure rolls back
the replacement. The tests verify that after a valid first insert and a failed
second insert, the earlier ledger survives unchanged.
The UI reports saved data only after transaction completion and explicit final
filesystem synchronization. A storage failure is different from a SQL constraint
failure: a commit might already have changed the in-memory ledger when a flush
fails. The error explains this uncertainty; export remains available. The
controlled final-sync failure test is injected, not a real quota exhaustion test.
Browser retention, power-loss durability and quota recovery are not certified.
Click **Export ledger CSV**, verify that the download exists, and store it
outside the browser. Choose that file to restore it, replacing the current
ledger. Tests and the browser run verify a round trip. This is a data-only
backup for this schema: IDs are regenerated, and schema, extensions, query
history and future tables are not included. It is not a PostgreSQL cluster backup.
Exports preserve raw cell values for round-trip import. Untrusted formula-leading
cells can be interpreted by spreadsheet software; inspect CSV as text or restore
it in this app rather than blindly opening an untrusted file in a spreadsheet.
## SQL and UI boundaries
The editor wraps one query as a subquery inside a read-only Postgres transaction,
returns at most 201 rows, and displays at most 200. An extra row indicates
truncation. The default total uses `float8`; with this lab's maximum 10,000 rows
and 100,000,000 cents per row, the integer sum stays within JavaScript's exact
integer range. Casting that sum to Postgres `integer` could overflow.
This is a local tool for queries you choose to run. It is not a sandbox for
hostile SQL. Read-only mode does not forbid every session-setting function.
The database runs on this page's main thread. Expensive SQL can block the tab;
the result limit does not bound all CPU/memory use. An attempted
`SET LOCAL statement_timeout = '1500ms'` followed by `SELECT pg_sleep(2)` did not
reject in our Node/PGlite 0.5.11 check, so the app makes no timeout guarantee.
Move execution into a terminable worker and define recovery before exposing it
to arbitrary untrusted queries.
Imported strings and result cells are rendered with `textContent`, not HTML.
The category chart uses the `live` extension; no chart dependency is installed.
The subscription watches the grouped query and updates after a changed ledger.
## Files and tests
- `core.mjs`: bounded CSV parsing, schema, transactional import, export format.
- `core.test.mjs`: six rule/engine test groups including rollback and sync failure.
- `query.mjs` / `query.test.mjs`: editor adapter and actual SQL, read-only sequence
rejection, row cap, recovery, and a valid sum above the int32 range.
- `app.mjs`, `index.html`, `style.css`: UI and one-tab ownership.
- `expenses.csv`: seven-row synthetic fixture.
- `build-offline.mjs`: build inventory, revisioned cache and generated service worker.
- `server.mjs`: loopback-only static server.
- `package.json`, `bun.lock`, `vite.config.mjs`: pinned build dependencies/config.
The Node suite has seven test groups. It runs actual Postgres through PGlite,
not a SQL mock. Browser results beside the ZIP record the observed environment,
exact SQL, document IDs, offline reload, CSV restore and tab ownership checks.
The source archive contains no dependencies, build output, real expenses or
browser runtime stores.
The synthetic CSV fixture, configuration and lockfile are also included in the ZIP.
Test recovery as well as the first query
The production application recovered the expected records after both online and offline reloads. Here are the observed behaviors:
| Check | Observed result |
|---|---|
| SQL correctness | Exact category results; 7 rows and 6700 cents overall |
| Atomic replacement | Database test preserved the previous ledger after a later constraint failure; browser rejected an invalid date without replacing its 7 rows |
| Reactive chart | Offline replacement fixture contained 8 rows, including one additional 100-cent Food expense; chart changed to €68.00 |
| Reload persistence | New document ID; the original 7 rows and 6700 cents remained |
| Offline operation | Queries and replacement import worked with browser-context networking disabled |
| Offline reload | Another new document ID; cached application reopened 8 rows and 6800 cents |
| Export and restore | Reimporting the exported CSV offline restored the original category results and 6700 cents |
| Tab ownership | Second tab waited with disabled controls, then acquired the database after the first closed |
The automated browser run used Chromium 153.0.8010.12 on Windows; the seven Node test groups passed using actual PGlite. The browser-results JSON retains the exact queries, observed values, document IDs and source hashes. The validation notes record the environment, injected storage-failure check and remaining limits. Desktop and 390-pixel layouts were also checked in Chrome 156.0.8078.48.
Offline testing used Playwright’s BrowserContext.setOffline(true) with service workers enabled. It checks a prepared application in that browser, rather than a first-ever offline visit or crash recovery.
Treat export as part of the product
Browser persistence is normally best-effort. Storage pressure, user clearing and private-session policies can remove it. Requesting persistent storage can improve retention, but it is not an external backup. The original CSV and the lab’s export provide a way to recover this dataset elsewhere. Quotas, persistence and eviction.
The CSV export is deliberately a data export for the fixed schema. It does not preserve arbitrary new tables, indexes or a changed database design. PGlite also offers dumpDataDir() and a WASM pg_dump tool for broader backup workflows; compatibility and upgrade requirements still need attention. Database archive API, dump tools, upgrade guidance.
Local execution also needs a clear privacy boundary. This lab has no import-upload endpoint or analytics dependency. Your own application can break that property with telemetry, remote scripts or output sharing. Browser storage is not an encrypted vault, and scripts executing on its origin can access application data.
When an embedded Postgres is useful
PGlite fits a personal CSV workbench, an offline report viewer or a prototype that benefits from actual relational queries and transactions. The Fresh executable experiment distributes a local HTTP server and stores editable JSON outside it. This experiment places the query engine and database in the browser, with browser storage governing retention.
Use a shared backend when the requirement is shared authoritative records, centralized authorization or access from another device. Adding those properties changes the architecture; embedding PostgreSQL does not supply them automatically.
For the CSV explorer, the payoff is concrete: one imported file becomes a constrained relational dataset, a SQL aggregate drives a chart, and the prepared application can reopen that dataset without a database server to maintain.
Licensing: PGlite offers Apache-2.0 or PostgreSQL licensing, with modifications to PostgreSQL source under the PostgreSQL license. Pinned licensing statement.
Prepared with AI assistance. Primary sources checked October 26, 2026; the companion validation record separates documentation claims from locally executed results.
