OPFS Private Origin File System
Persist progress files in the origin-private file system: getDirectory, a writable handle, and estimate() quota reporting in one flow.
Code
// OPFS (origin-private file system) gives each origin a private, persistent
// file area: navigator.storage.getDirectory() returns the root handle.
if (typeof navigator === "undefined" || !navigator.storage?.getDirectory) {
console.log("OPFS needs a browser with navigator.storage.getDirectory");
} else {
const root = await navigator.storage.getDirectory();
const handle = await root.getFileHandle("progress.json", { create: true });
const writable = await handle.createWritable();
await writable.write(JSON.stringify({ step: 3, of: 5 }));
await writable.close();
const readBack = await (await root.getFileHandle("progress.json")).getFile();
console.log("stored:", await readBack.text());
const usage = (await navigator.storage.estimate()).usage ?? 0;
console.log("quota usage reported:", usage >= 0);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
OPFS needs a browser with navigator.storage.getDirectoryWhat happens when it runs
OPFS Private Origin File System defines no custom function — the whole flow runs at the top level, guarded by an if/else check on navigator.storage?.getDirectory, and usage is a top-level const holding the quota number from navigator.storage.estimate().
The asynchronous flow is linearized with await, keeping failure handling local.
Caveats
- Nothing to vet in a supply-chain review — the file pulls in no packages.
navigatorexist only in browsers — a Node runtime has no shims for them out of the box.
Using it
Signature: const usage = (await navigator.storage.estimate()).usage ?? 0;
Output lines are prefixed (stored:, quota usage reported:), which keeps the effect of each step in plain sight.
Key statements
const usage = (await navigator.storage.estimate()).usage ?? 0;
await writable.write(JSON.stringify({ step: 3, of: 5 }));
const readBack = await (await root.getFileHandle("progress.json")).getFile();
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `usage` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.