Origin Private File System (OPFS) in React: Synchronous Worker Storage and High-Speed Binary Persistence
Client-side React applications are increasingly managing desktop-class workloads—local SQLite/Wasm databases, multi-track audio/video editors, AI model weight caches, and large offline analytics datasets. While IndexedDB has long served as the browser's primary structured storage engine, it suffers from asynchronous transaction overhead, serialization costs, and poor throughput when performing frequent byte-range updates on large binary files.
Similarly, the user-visible File System Access API (showOpenFilePicker) requires explicit permission prompts and writes through temporary swap files with Safe Browsing checks, making it too slow for high-frequency random-access writes.
The Origin Private File System (OPFS) solves both problems. Provided as a private, origin-partitioned storage endpoint via StorageManager.getDirectory(), OPFS requires zero permission prompts, supports in-place byte-level writes, and exposes the ultra-fast FileSystemSyncAccessHandle interface inside dedicated Web Workers.
In this architectural guide, we build a high-speed OPFS storage pipeline in React: contrasting main-thread async access with worker-scoped synchronous handles, implementing a typed Web Worker storage bridge, building a useOPFS React hook, and managing storage quotas cleanly.
Main-Thread Async OPFS vs. Worker Synchronous Handles
+-----------------------------------------------------------------------+
| React Main Thread |
| • navigator.storage.getDirectory() (Async Promises) |
| • Good for: listing files, reading small blobs, quota estimates |
+-----------------------------------+-----------------------------------+
| postMessage()
v
+-----------------------------------------------------------------------+
| Dedicated Web Worker |
| • fileHandle.createSyncAccessHandle() |
| • Synchronous I/O: read(), write(), truncate(), getSize(), flush() |
| • Zero Promise overhead, in-place byte offsets, exclusive file lock |
+-----------------------------------------------------------------------+
Why FileSystemSyncAccessHandle Is Significantly Faster
When you call FileSystemFileHandle.createSyncAccessHandle() inside a Dedicated Web Worker:
- Zero Promise Microtask Overhead: Methods like
read(),write(),getSize(),truncate(),flush(), andclose()execute synchronously without allocating Promises per chunk. - In-Place Random Access: You can write 4 KB pages at arbitrary byte offsets (
{ at: offset }) without rewriting the entire file—making it ideal for SQLite-Wasm pages or append-only binary logs. - Exclusive File Locking: By default (
mode: 'readwrite'), creating a sync access handle acquires an exclusive lock on the file, preventing concurrent corruption untilclose()is called.
Step 1: The OPFS Web Worker (opfs.worker.ts)
Because synchronous disk I/O is forbidden on the browser's main UI thread, we encapsulate all FileSystemSyncAccessHandle operations inside a dedicated Web Worker:
// workers/opfs.worker.ts
export type OPFSRequest =
| { id: string; type: 'WRITE_BYTES'; fileName: string; data: ArrayBuffer; offset?: number }
| { id: string; type: 'READ_BYTES'; fileName: string }
| { id: string; type: 'LIST_FILES' }
| { id: string; type: 'DELETE_FILE'; fileName: string };
export type OPFSResponse =
| { id: string; ok: true; payload: unknown }
| { id: string; ok: false; error: string };
const encoder = new TextEncoder();
async function getRoot(): Promise<FileSystemDirectoryHandle> {
return navigator.storage.getDirectory();
}
self.onmessage = async (event: MessageEvent<OPFSRequest>) => {
const req = event.data;
try {
const root = await getRoot();
switch (req.type) {
case 'WRITE_BYTES': {
const handle = await root.getFileHandle(req.fileName, { create: true });
const accessHandle = await handle.createSyncAccessHandle();
try {
const view = new Uint8Array(req.data);
const offset = req.offset ?? 0;
if (offset === 0) {
accessHandle.truncate(0);
}
const bytesWritten = accessHandle.write(view, { at: offset });
accessHandle.flush();
self.postMessage({
id: req.id,
ok: true,
payload: { bytesWritten, size: accessHandle.getSize() },
} satisfies OPFSResponse);
} finally {
// Always release the exclusive file lock
accessHandle.close();
}
break;
}
case 'READ_BYTES': {
const handle = await root.getFileHandle(req.fileName);
const accessHandle = await handle.createSyncAccessHandle({ mode: 'read-only' });
try {
const size = accessHandle.getSize();
const buffer = new ArrayBuffer(size);
accessHandle.read(new Uint8Array(buffer), { at: 0 });
// Transfer ArrayBuffer back with zero copy
self.postMessage(
{ id: req.id, ok: true, payload: buffer } satisfies OPFSResponse,
[buffer]
);
} finally {
accessHandle.close();
}
break;
}
case 'LIST_FILES': {
const entries: Array<{ name: string; size: number }> = [];
for await (const [name, handle] of (root as any).entries()) {
if (handle.kind === 'file') {
const file = await handle.getFile();
entries.push({ name, size: file.size });
}
}
self.postMessage({ id: req.id, ok: true, payload: entries } satisfies OPFSResponse);
break;
}
case 'DELETE_FILE': {
await root.removeEntry(req.fileName);
self.postMessage({ id: req.id, ok: true, payload: true } satisfies OPFSResponse);
break;
}
}
} catch (err) {
self.postMessage({
id: req.id,
ok: false,
error: err instanceof Error ? err.message : String(err),
} satisfies OPFSResponse);
}
};
Note on Locking Modes: Passing
{ mode: 'read-only' }tocreateSyncAccessHandle()allows multiple tabs or workers to read the same OPFS file concurrently, whereas the default'readwrite'mode enforces a single exclusive lock (throwingNoModificationAllowedErrorif another handle is open).
Step 2: The React Orchestration Hook (useOPFS.ts)
Next, we wrap the worker RPC protocol in a clean React hook that manages pending request promises, cleans up the worker on unmount, and queries navigator.storage.estimate() for quota visibility:
// hooks/useOPFS.ts
import { useEffect, useRef, useState, useCallback } from 'react';
import type { OPFSRequest, OPFSResponse } from '../workers/opfs.worker';
export interface OPFSFileEntry {
name: string;
size: number;
}
export function useOPFS() {
const workerRef = useRef<Worker | null>(null);
const pendingRef = useRef<
Map<string, { resolve: (val: any) => void; reject: (err: Error) => void }>
>(new Map());
const [files, setFiles] = useState<OPFSFileEntry[]>([]);
const [quotaInfo, setQuotaInfo] = useState<{ usageMB: string; quotaMB: string } | null>(null);
const [isSupported] = useState<boolean>(
() => typeof navigator !== 'undefined' && 'storage' in navigator && 'getDirectory' in navigator.storage
);
const sendRequest = useCallback(
<T,>(message: Omit<OPFSRequest, 'id'>, transfer: Transferable[] = []): Promise<T> => {
return new Promise((resolve, reject) => {
if (!workerRef.current) {
reject(new Error('OPFS worker is not initialized.'));
return;
}
const id = crypto.randomUUID();
pendingRef.current.set(id, { resolve, reject });
workerRef.current.postMessage({ ...message, id } as OPFSRequest, transfer);
});
},
[]
);
const refreshFiles = useCallback(async () => {
if (!isSupported) return;
const list = await sendRequest<OPFSFileEntry[]>({ type: 'LIST_FILES' });
setFiles(list);
if (navigator.storage?.estimate) {
const { usage = 0, quota = 0 } = await navigator.storage.estimate();
setQuotaInfo({
usageMB: (usage / (1024 * 1024)).toFixed(2),
quotaMB: (quota / (1024 * 1024)).toFixed(0),
});
}
}, [isSupported, sendRequest]);
useEffect(() => {
if (!isSupported) return;
const worker = new Worker(new URL('../workers/opfs.worker.ts', import.meta.url), {
type: 'module',
});
workerRef.current = worker;
worker.onmessage = (event: MessageEvent<OPFSResponse>) => {
const res = event.data;
const pending = pendingRef.current.get(res.id);
if (!pending) return;
pendingRef.current.delete(res.id);
if (res.ok) {
pending.resolve(res.payload);
} else {
pending.reject(new Error(res.error));
}
};
refreshFiles().catch(console.error);
return () => {
worker.terminate();
workerRef.current = null;
pendingRef.current.clear();
};
}, [isSupported, refreshFiles]);
const writeTextFile = useCallback(
async (fileName: string, text: string) => {
const buffer = new TextEncoder().encode(text).buffer;
const result = await sendRequest<{ bytesWritten: number; size: number }>(
{ type: 'WRITE_BYTES', fileName, data: buffer },
[buffer]
);
await refreshFiles();
return result;
},
[refreshFiles, sendRequest]
);
const readTextFile = useCallback(
async (fileName: string): Promise<string> => {
const buffer = await sendRequest<ArrayBuffer>({ type: 'READ_BYTES', fileName });
return new TextDecoder().decode(buffer);
},
[sendRequest]
);
const deleteFile = useCallback(
async (fileName: string) => {
await sendRequest({ type: 'DELETE_FILE', fileName });
await refreshFiles();
},
[refreshFiles, sendRequest]
);
return {
isSupported,
files,
quotaInfo,
writeTextFile,
readTextFile,
deleteFile,
};
}
Step 3: Production OPFS Scratchpad Component
Here is a complete React UI for writing, inspecting, and deleting sandboxed OPFS files via the background worker:
// components/OPFSScratchpad.tsx
import React, { useState } from 'react';
import { useOPFS } from '../hooks/useOPFS';
export function OPFSScratchpad() {
const { isSupported, files, quotaInfo, writeTextFile, readTextFile, deleteFile } = useOPFS();
const [fileName, setFileName] = useState('session-snapshot.json');
const [content, setContent] = useState('{
"status": "ready",
"nodes": 1024
}');
const [statusMsg, setStatusMsg] = useState<string>('');
if (!isSupported) {
return (
<div className="max-w-xl mx-auto p-6 bg-slate-900 border border-slate-800 rounded-2xl text-amber-400 text-sm">
Origin Private File System is unavailable in this context (requires HTTPS).
</div>
);
}
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
if (!fileName.trim()) return;
const res = await writeTextFile(fileName.trim(), content);
setStatusMsg(`Wrote ${res.bytesWritten} bytes synchronously in worker.`);
};
const handleLoad = async (name: string) => {
const text = await readTextFile(name);
setFileName(name);
setContent(text);
setStatusMsg(`Loaded ${name} from OPFS.`);
};
return (
<div className="max-w-2xl mx-auto p-6 bg-slate-900 border border-slate-800 rounded-2xl shadow-xl space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-800 pb-4">
<div>
<h2 className="text-lg font-bold text-white">OPFS Worker Storage</h2>
<p className="text-xs text-slate-400">
Zero-prompt sandboxed disk I/O via FileSystemSyncAccessHandle.
</p>
</div>
{quotaInfo && (
<span className="px-3 py-1 text-xs font-mono rounded-full bg-slate-950 border border-slate-800 text-sky-400">
{quotaInfo.usageMB} MB / {quotaInfo.quotaMB} MB
</span>
)}
</div>
<form onSubmit={handleSave} className="space-y-3">
<div className="flex gap-2">
<input
type="text"
value={fileName}
onChange={(e) => setFileName(e.target.value)}
placeholder="Filename (e.g., cache.bin)"
className="flex-1 px-3 py-2 rounded-lg bg-slate-950 border border-slate-700 text-white text-xs font-mono focus:outline-none focus:ring-2 focus:ring-sky-500"
/>
<button
type="submit"
className="px-4 py-2 text-xs font-semibold rounded-lg bg-sky-500 hover:bg-sky-600 text-white transition"
>
Write to OPFS
</button>
</div>
<textarea
rows={5}
value={content}
onChange={(e) => setContent(e.target.value)}
className="w-full p-3 rounded-xl bg-slate-950 border border-slate-800 text-slate-200 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-sky-500"
/>
</form>
{statusMsg && <p className="text-xs font-mono text-emerald-400">{statusMsg}</p>}
<div className="space-y-2">
<h3 className="text-xs font-mono uppercase text-slate-400">Stored OPFS Files</h3>
{files.length === 0 ? (
<p className="text-xs text-slate-500">No files in origin private directory yet.</p>
) : (
files.map((file) => (
<div
key={file.name}
className="flex items-center justify-between p-3 rounded-xl bg-slate-950 border border-slate-800 text-xs"
>
<span className="font-mono text-slate-200">
{file.name} <span className="text-slate-500">({file.size} B)</span>
</span>
<div className="flex gap-2">
<button
type="button"
onClick={() => handleLoad(file.name)}
className="px-2.5 py-1 rounded bg-slate-800 hover:bg-slate-700 text-sky-400"
>
Load
</button>
<button
type="button"
onClick={() => deleteFile(file.name)}
className="px-2.5 py-1 rounded bg-rose-950 hover:bg-rose-900 text-rose-300"
>
Delete
</button>
</div>
</div>
))
)}
</div>
</div>
);
}
Architectural Comparison & Best Practices
| Storage Engine | IndexedDB | User-Visible File System API | Origin Private File System (OPFS) |
|---|---|---|---|
| Permission Prompts | None | Explicit OS file picker required | None (origin-sandboxed) |
| Worker Sync I/O | ❌ Async transactions only | ❌ Async FileSystemWritableFileStream | Synchronous FileSystemSyncAccessHandle |
| In-Place Byte Writes | ❌ Rewrites whole record | ❌ Swaps via temp file | Direct byte-offset writes |
| Browser Support | Universal | Chromium desktop | Baseline across Chrome, Firefox, Safari |
| Ideal Use Case | Structured JSON & key-value indexes | Exporting/editing user OS files | SQLite-Wasm, media buffers, AI model caches |
Key Production Best Practices
- Always Close
FileSystemSyncAccessHandleintry...finally: Leaving a handle open retains an exclusive lock on the file, causing subsequent worker operations or tabs to fail withNoModificationAllowedError. - Handle Private Browsing Exceptions: Calling
navigator.storage.getDirectory()in private/incognito browsing modes can reject withSecurityErrororUnknownErrorin some browsers. Always guard initialization withtry/catchand fall back gracefully. - Transfer
ArrayBuffers Zero-Copy: When sending binary payloads between React and the OPFS worker, include[buffer]inpostMessage()'s transfer list to avoid duplicating multi-megabyte buffers in memory.
Conclusion
The Origin Private File System (OPFS) fills the missing high-throughput binary storage layer in modern React architectures. By running synchronous FileSystemSyncAccessHandle operations inside a dedicated Web Worker and bridging them through a typed React hook, applications gain near-native disk performance, zero permission friction, and full cross-browser Baseline reliability.