Local-First File Editing in React: File System Access API, Handle Persistence, and Streaming Saves
For decades, browser-based productivity tools—code editors, markdown notebooks, CSV transformers, and image utilities—suffered from a clumsy file workflow. To edit a local file, users had to upload it via <input type="file">, edit an in-memory copy, and then download a brand-new document (1).md file back to their Downloads folder. Saving changes directly back to the original file on disk was impossible without wrapping the web app in Electron.
The File System API (specifically its File System Access extensions) changes this paradigm. Modern browsers can now request explicit user permission to read and write directly to files and directories on the user's local device.
However, integrating native disk handles into React introduces distinct architectural requirements:
- User Activation Constraints: Methods like window.showOpenFilePicker() and window.showSaveFilePicker() throw a
SecurityErrorunless invoked directly inside a user gesture (such as a buttononClick). - Handle Persistence Across Reloads: A
FileSystemFileHandlecannot be stored inlocalStoragebecause it is not JSON-serializable, yet it is structured-cloneable and can be persisted inIndexedDB. - Permission Re-Verification: Restoring a handle from
IndexedDBafter a page refresh does not automatically grant write access; your app must query and re-requestreadwritepermissions cleanly. - Atomic Writes & Safe Fallbacks: Writing to disk via FileSystemWritableFileStream stages changes in a temporary file and swaps atomically on
.close(), while unsupported browsers still require a graceful<input>+Blobdownload fallback.
In this architectural guide, we build a complete local-first file editor pipeline in React: encapsulating file pickers in a custom useLocalFile hook, persisting handles in IndexedDB, managing permissions, and implementing progressive enhancement fallbacks.
How the File System Access Pipeline Works
+-----------------------------------------------------------------------+
| React UI (User Gesture: "Open File" / "Save") |
+-----------------------------------+-----------------------------------+
|
+-------------------------+-------------------------+
| |
v (Supported: Chromium) v (Fallback: Firefox/Safari)
[showOpenFilePicker()] [<input type="file"> + Blob URL]
| |
v v
[FileSystemFileHandle] [In-Memory File Copy + Download]
| |
| +---> [Store Handle in IndexedDB] (Survives Page Refresh)
v
[handle.createWritable()] ---> [FileSystemWritableFileStream] ---> [Atomic Disk Swap on .close()]
Key Security Guarantees
- Explicit Consent: Web apps can never silently browse arbitrary paths. The OS-native picker only exposes the exact file or directory selected by the user.
- Origin & HTTPS Isolation: File System Access methods require a secure context (HTTPS) and cannot be called from cross-origin iframes.
- Safe-Browsing Checks: Browsers write changes to a temporary swap file first and only replace the target file once
writable.close()completes without error.
Persisting FileSystemFileHandle in IndexedDB
Unlike strings or plain JSON objects, FileSystemFileHandle instances implement the structured clone algorithm. That means you can save them directly into IndexedDB so users can reopen their last edited document with one click after refreshing the tab:
// utils/handleStorage.ts
const DB_NAME = 'local_file_handles_db';
const STORE_NAME = 'handles';
function openHandleDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, 1);
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function saveFileHandle(
key: string,
handle: FileSystemFileHandle
): Promise<void> {
const db = await openHandleDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite');
tx.objectStore(STORE_NAME).put(handle, key);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
export async function loadFileHandle(
key: string
): Promise<FileSystemFileHandle | null> {
const db = await openHandleDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readonly');
const request = tx.objectStore(STORE_NAME).get(key);
request.onsuccess = () => resolve(request.result ?? null);
request.onerror = () => reject(request.error);
});
}
Verifying Permissions on Restored Handles
When a user returns to your React app and loads a FileSystemFileHandle from IndexedDB, the browser resets active write permissions for security. Calling handle.createWritable() without checking permissions first will throw NotAllowedError.
Always run a permission verification helper inside a user-initiated action (like a "Reconnect Recent File" button):
// utils/filePermissions.ts
export async function verifyPermission(
handle: FileSystemFileHandle,
mode: 'read' | 'readwrite' = 'readwrite'
): Promise<boolean> {
const options = { mode };
// 1. Check if permission was already granted in this session
if ((await handle.queryPermission(options)) === 'granted') {
return true;
}
// 2. Request permission (must be triggered by a user gesture)
if ((await handle.requestPermission(options)) === 'granted') {
return true;
}
return false;
}
Building the useLocalFile React Hook
Let's encapsulate feature detection, opening, saving in place, "Save As", and fallback downloads inside a clean TypeScript hook:
// hooks/useLocalFile.ts
import { useState, useCallback, useEffect } from 'react';
import { saveFileHandle, loadFileHandle } from '../utils/handleStorage';
import { verifyPermission } from '../utils/filePermissions';
const RECENT_HANDLE_KEY = 'last_opened_markdown';
export function useLocalFile() {
const [fileHandle, setFileHandle] = useState<FileSystemFileHandle | null>(null);
const [fileName, setFileName] = useState<string>('untitled.md');
const [content, setContent] = useState<string>('');
const [isDirty, setIsDirty] = useState<boolean>(false);
const [isSaving, setIsSaving] = useState<boolean>(false);
const [recentHandle, setRecentHandle] = useState<FileSystemFileHandle | null>(null);
const [error, setError] = useState<string | null>(null);
const isSupported =
typeof window !== 'undefined' && 'showOpenFilePicker' in window;
// Load any previously saved handle metadata on mount
useEffect(() => {
if (!isSupported) return;
loadFileHandle(RECENT_HANDLE_KEY)
.then((handle) => {
if (handle) setRecentHandle(handle);
})
.catch(() => {
// Ignore IndexedDB errors in private browsing modes
});
}, [isSupported]);
// Open an existing file from disk
const openFile = useCallback(async () => {
setError(null);
if (!isSupported) {
setError('File System Access API is not supported in this browser.');
return;
}
try {
const [handle] = await window.showOpenFilePicker({
multiple: false,
types: [
{
description: 'Markdown & Text Files',
accept: { 'text/markdown': ['.md', '.markdown'], 'text/plain': ['.txt'] },
},
],
});
const file = await handle.getFile();
const text = await file.text();
setFileHandle(handle);
setFileName(handle.name);
setContent(text);
setIsDirty(false);
await saveFileHandle(RECENT_HANDLE_KEY, handle);
setRecentHandle(handle);
} catch (err) {
if ((err as Error).name !== 'AbortError') {
setError((err as Error).message);
}
}
}, [isSupported]);
// Reopen the persisted handle after a page reload
const reopenRecentFile = useCallback(async () => {
if (!recentHandle) return;
setError(null);
try {
const granted = await verifyPermission(recentHandle, 'readwrite');
if (!granted) {
setError('Permission to access the recent file was denied.');
return;
}
const file = await recentHandle.getFile();
const text = await file.text();
setFileHandle(recentHandle);
setFileName(recentHandle.name);
setContent(text);
setIsDirty(false);
} catch (err) {
setError((err as Error).message);
}
}, [recentHandle]);
// Save directly to disk in place (or trigger Save As / Download fallback)
const saveFile = useCallback(async () => {
setError(null);
// Fallback for browsers without showSaveFilePicker
if (!isSupported) {
const blob = new Blob([content], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = fileName;
anchor.click();
URL.revokeObjectURL(url);
setIsDirty(false);
return;
}
setIsSaving(true);
try {
let targetHandle = fileHandle;
if (!targetHandle) {
targetHandle = await window.showSaveFilePicker({
suggestedName: fileName,
types: [
{
description: 'Markdown File',
accept: { 'text/markdown': ['.md'] },
},
],
});
setFileHandle(targetHandle);
setFileName(targetHandle.name);
await saveFileHandle(RECENT_HANDLE_KEY, targetHandle);
setRecentHandle(targetHandle);
}
const hasPermission = await verifyPermission(targetHandle, 'readwrite');
if (!hasPermission) {
setError('Write permission is required to save changes.');
return;
}
// Stream write to temporary file, then commit atomically on close()
const writable = await targetHandle.createWritable();
await writable.write(content);
await writable.close();
setIsDirty(false);
} catch (err) {
if ((err as Error).name !== 'AbortError') {
setError((err as Error).message);
}
} finally {
setIsSaving(false);
}
}, [content, fileHandle, fileName, isSupported]);
const updateContent = useCallback((nextText: string) => {
setContent(nextText);
setIsDirty(true);
}, []);
return {
isSupported,
fileName,
content,
isDirty,
isSaving,
hasActiveHandle: Boolean(fileHandle),
recentFileName: recentHandle?.name ?? null,
error,
openFile,
reopenRecentFile,
saveFile,
updateContent,
};
}
Production Component: Local Markdown Editor
Here is a clean, developer-ready editor UI wired to useLocalFile, including Cmd+S / Ctrl+S save interception and a one-click reconnect banner for persisted handles:
// components/LocalMarkdownEditor.tsx
import React, { useEffect } from 'react';
import { useLocalFile } from '../hooks/useLocalFile';
export function LocalMarkdownEditor() {
const {
isSupported,
fileName,
content,
isDirty,
isSaving,
hasActiveHandle,
recentFileName,
error,
openFile,
reopenRecentFile,
saveFile,
updateContent,
} = useLocalFile();
// Bind Cmd+S / Ctrl+S to save directly to disk
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
e.preventDefault();
saveFile();
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [saveFile]);
return (
<div className="max-w-3xl mx-auto p-6 bg-slate-900 border border-slate-800 rounded-2xl shadow-xl space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-800 pb-4">
<div>
<div className="flex items-center gap-2">
<h2 className="text-lg font-bold text-white font-mono">{fileName}</h2>
{isDirty && (
<span className="px-2 py-0.5 text-[10px] font-semibold rounded-full bg-amber-500/20 text-amber-300">
Unsaved
</span>
)}
</div>
<p className="text-xs text-slate-400">
{isSupported
? 'Native File System Access active (in-place disk saves)'
: 'Fallback mode (saves via browser download)'}
</p>
</div>
<div className="flex items-center gap-2">
{recentFileName && !hasActiveHandle && (
<button
onClick={reopenRecentFile}
className="px-3 py-1.5 text-xs font-semibold rounded-lg bg-slate-800 text-sky-400 hover:bg-slate-700 transition"
>
Reopen {recentFileName}
</button>
)}
<button
onClick={openFile}
className="px-3 py-1.5 text-xs font-semibold rounded-lg bg-slate-800 text-slate-200 hover:bg-slate-700 transition"
>
Open File
</button>
<button
onClick={saveFile}
disabled={isSaving}
className="px-4 py-1.5 text-xs font-semibold rounded-lg bg-sky-500 text-white hover:bg-sky-600 disabled:opacity-50 transition"
>
{isSaving ? 'Saving...' : 'Save (Cmd/Ctrl+S)'}
</button>
</div>
</div>
{error && (
<div className="p-3 rounded-lg bg-rose-950/60 border border-rose-800 text-xs text-rose-300">
{error}
</div>
)}
<textarea
value={content}
onChange={(e) => updateContent(e.target.value)}
placeholder="Open a local .md file or start typing..."
rows={14}
className="w-full p-4 rounded-xl bg-slate-950 border border-slate-800 text-slate-200 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-sky-500 resize-y"
/>
</div>
);
}
Architectural Trade-Offs & Best Practices
| Capability | Classic <input type="file"> + Download | Origin Private File System (OPFS) | File System Access API (showOpenFilePicker) |
|---|---|---|---|
| In-Place Disk Saves | ❌ Always creates duplicate downloads | ❌ Isolated inside browser origin sandbox | Writes directly to user-chosen path |
| User-Visible Files | Standard OS files | ❌ Hidden from user's OS Finder/Explorer | Reads/writes real user files |
| Cross-Browser Support | Universal | Broad (Chromium, Firefox, Safari) | Chromium desktop browsers (needs fallback) |
| Ideal Use Case | One-off form uploads & exports | High-speed SQLite/Wasm scratch disks | Local IDEs, markdown editors, media tools |
Key Production Best Practices
- Always Catch
AbortError: Pressing Cancel in the OS file dialog rejects the promise withAbortError. Treat this as a normal cancellation rather than surfacing an error banner to the user. - Close Writable Streams in
try...finally: Leaving aFileSystemWritableFileStreamunclosed locks the temporary swap file and discards all buffered writes. Always ensurewritable.close()executes cleanly. - Pair with Origin Private File System (OPFS) for Scratch Data: If your app needs high-frequency autosaves without prompting for user permissions on every session, store drafts in OPFS and use
showSaveFilePicker()only when exporting to the user's visible filesystem.
Conclusion
The File System Access API bridges the final usability gap between native desktop utilities and modern React web apps. By encapsulating showOpenFilePicker, FileSystemWritableFileStream, IndexedDB handle persistence, and graceful download fallbacks into a cohesive React hook, developers can deliver genuine local-first editing workflows with zero server storage overhead.