Guide · Browser storage

OPFS in multiple tabs: fixing NoModificationAllowedError

Your OPFS code works perfectly until a user opens your app in a second tab. Then it fails with NoModificationAllowedError, or in Safari with an InvalidStateError that doesn't mention locks at all. I checked whether this is still a problem in November 2026 by testing Chrome, Firefox and Safari's engine, and I tested every fix below in all three.

The short answer

  • Yes, it still happens. createSyncAccessHandle() locks the file exclusively by default in every browser, so the second tab that opens the same file fails.
  • Safari reports it differently. Chrome and Firefox throw NoModificationAllowedError. Safari's engine throws InvalidStateError. Catch both.
  • The readwrite-unsafe fix only works in Chromium. Firefox and Safari ignore the option without an error and lock the file anyway.
  • The fix that works everywhere: wrap short file operations in a Web Lock. For a file you keep open, like a SQLite database, let one leader tab own it and have the other tabs send it requests.

Still deciding whether OPFS is the right storage at all? IndexedDB handles several tabs for you through transactions. My OPFS vs IndexedDB benchmark shows when OPFS is worth this extra work.

Does the problem still exist? What I tested

I ran the same test in Chromium 159, Firefox 159 and WebKit 27.2 (the engine behind Safari) on an M1 MacBook Air, using Playwright with a normal, persistent browser profile. Each test opened the same OPFS file from dedicated workers in two separate tabs.

Second tab tries to…ChromeFirefoxSafari (WebKit)
Open a sync access handle (default)NoModificationAllowedErrorNoModificationAllowedErrorInvalidStateError
Open a writable stream with createWritable()NoModificationAllowedErrorNoModificationAllowedErrorInvalidStateError
Open with mode: "read-only" in both tabsWorksFailsFails
Open with mode: "readwrite-unsafe" in both tabsWorksFailsFails
Read it with getFile()WorksWorksWorks
Delete it with removeEntry()NoModificationAllowedErrorNoModificationAllowedErrorNoModificationAllowedError
Open it after the first tab closesWorksWorksWorks

The lock is by design. The File System standard says a sync access handle locks its file, and the MDN reference for createSyncAccessHandle() documents the error. What changed is that Chromium added the mode option to relax it, and the other engines haven't. The WebKit request for readwrite-unsafe, filed in December 2024, was still unassigned in November 2026.

The lock doesn't only fail when two tabs open the file at exactly the same moment. Three tabs each opening, updating and closing a small file 20 times in parallel, without any coordination, kept colliding:

Failed opens out of 60: no lock vs Web Locks60 parallel opens of the same OPFS file from three tabs, median of five runs. Without a lock, Chrome failed 33, Firefox 54 and Safari's engine 15. With Web Locks, none failed in any browser.No lockWeb LocksChromeChrome · no lock: 33 of 60 failed33 of 60Chrome · Web Locks: 0 failed0FirefoxFirefox · no lock: 54 of 60 failed54 of 60Firefox · Web Locks: 0 failed0Safari (WebKit)Safari (WebKit) · no lock: 15 of 60 failed15 of 60Safari (WebKit) · Web Locks: 0 failed0
Failed opens out of 60, three tabs × 20 parallel updates, median of 5 runs. Fewer is better.

With a Web Lock around the same code, nothing failed, and the shared counter ended at exactly 60 in every browser, with no updates lost.

Three traps that make it worse

1. Safari throws a different error

WebKit reports the conflict as InvalidStateError: The object is in an invalid state. Code like if (e.name === "NoModificationAllowedError") retry() never retries in Safari. In a private WebKit session it was worse: every OPFS call failed with UnknownError and a message about an "unknown transient reason (e.g. out of memory)", which is just OPFS being unavailable there.

JavaScript · detect a lock conflict in every browser
const isLockError = (e) =>
  e?.name === "NoModificationAllowedError" || // Chrome, Firefox
  e?.name === "InvalidStateError";            // Safari

2. Firefox and Safari ignore the mode option

Passing { mode: "readwrite-unsafe" } doesn't throw in Firefox or Safari. They simply don't read the option and hand you an exclusive handle, so the code looks fine until the second tab arrives. That applies to "read-only" as well: in my tests two read-only handles collided in both browsers. The Emscripten OPFS backend describes the same behaviour.

You can detect support by checking whether the browser actually reads the option:

JavaScript · inside a dedicated worker
async function supportsLockModes(fileHandle) {
  let read = false;
  const probe = await fileHandle.createSyncAccessHandle({
    get mode() { read = true; return "readwrite"; },
  });
  probe.close();
  return read; // true in Chromium, false in Firefox and Safari
}

It opens a normal handle for a moment, so run it once at startup on a file no other tab is using, and cache the result.

3. Two writable streams don't fail, they overwrite

On the main thread, createWritable() from two tabs at once worked in all three browsers. Each writer gets its own temporary copy, and whichever closes last replaces the whole file. No error, just one tab's changes silently gone. Treat writable streams like sync handles and put them behind a lock too.

Fix 1: Web Locks for short operations

If your code opens a file, does some work and closes it again, wrap that in the Web Locks API. A lock with the same name is shared by every tab and worker on your site. The browser queues the requests and releases the lock automatically when the callback finishes or the tab closes.

JavaScript · opfs.worker.js
async function withFile(name, fn) {
  return navigator.locks.request(`opfs:${name}`, async () => {
    const root = await navigator.storage.getDirectory();
    const file = await root.getFileHandle(name, { create: true });
    const handle = await file.createSyncAccessHandle();
    try {
      return await fn(handle);
    } finally {
      handle.close(); // always close before the lock is released
    }
  });
}

// Example: a counter several tabs can update safely
const next = await withFile("counter.bin", (handle) => {
  const value = new Uint32Array(1);
  handle.read(value, { at: 0 });
  value[0]++;
  handle.write(value, { at: 0 });
  handle.flush();
  return value[0];
});

In my test the second tab simply waited for the first to finish (about 200 ms, the time I held the file open), then succeeded. Keep the work inside the lock short. Every other tab waits for it.

Use this for exports, logs, settings files and caches: anything you can open, change and close in one go.

Fix 2: a leader tab for files you keep open

Some files are too expensive to open and close all the time. A SQLite database, or a large file with records at fixed positions, works best with one handle that stays open. Then the rule is simple: one tab owns the file, and the others ask that tab to do the work.

Leader tab pattern for OPFSTabs 2 and 3 send requests over a BroadcastChannel to tab 1, the leader, which holds a Web Lock. Only the leader's dedicated worker opens the OPFS file.Only this tab touches the fileTab 2followerTab 3followerBroadcastChannelTab 1 · leaderholds the Web LockDedicated workeropens the file once
When the leader tab closes, the next tab in line gets the lock and takes over.

The Web Locks API picks the leader. Every tab asks for the same lock and never releases it, so the first one gets it and the others wait in line. That gives you automatic failover for free.

JavaScript · db-client.js (loaded in every tab)
const channel = new BroadcastChannel("app-db");
const waiting = new Map(); // request id -> { resolve, reject, timer }
let worker = null;         // only set in the leader tab

function settle({ id, result, error }) {
  const p = waiting.get(id);
  if (!p) return;
  waiting.delete(id);
  clearTimeout(p.timer);
  error ? p.reject(new Error(error)) : p.resolve(result);
}

// Replies from the leader tab
channel.addEventListener("message", ({ data }) => {
  if (!data.op) settle(data);
});

// The first tab to get this lock becomes the leader; the rest wait in line
navigator.locks.request("app-db-leader", () => {
  worker = new Worker("/db.worker.js");
  worker.onmessage = ({ data }) => {
    if (waiting.has(data.id)) settle(data); // our own request
    else channel.postMessage(data);         // a reply for another tab
  };
  channel.addEventListener("message", ({ data }) => {
    if (data.op) worker.postMessage(data);  // a request from another tab
  });
  return new Promise(() => {});             // hold the lock until this tab closes
});

export function db(op, ...args) {
  const msg = { id: crypto.randomUUID(), op, args };
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      waiting.delete(msg.id);
      reject(new Error("No reply from the leader tab"));
    }, 5000);
    waiting.set(msg.id, { resolve, reject, timer });
    if (worker) worker.postMessage(msg);
    else channel.postMessage(msg);
  });
}
JavaScript · db.worker.js (runs only in the leader tab)
let handle;
const ready = (async () => {
  const root = await navigator.storage.getDirectory();
  const file = await root.getFileHandle("app.log", { create: true });
  handle = await file.createSyncAccessHandle();
})();

const ops = {
  append(text) {
    const bytes = new TextEncoder().encode(text + "\n");
    handle.write(bytes, { at: handle.getSize() });
    handle.flush();
    return handle.getSize();
  },
  readAll() {
    const buf = new Uint8Array(handle.getSize());
    handle.read(buf, { at: 0 });
    return new TextDecoder().decode(buf);
  },
};

onmessage = async ({ data: { id, op, args } }) => {
  try {
    await ready;
    postMessage({ id, result: ops[op](...args) });
  } catch (e) {
    postMessage({ id, error: `${e.name}: ${e.message}` });
  }
};

Every tab then uses the same call, wherever the file actually lives: await db("append", "hello"). I tested it with three tabs appending at the same time, then closed the leader tab. The next tab took over within half a second and the file kept every line.

Two things to handle in a real app:

  • Requests in flight when the leader closes are lost. The timeout rejects them. Retry operations that are safe to repeat.
  • Why not a SharedWorker? In Chrome and Firefox, createSyncAccessHandle() isn't available in a SharedWorker, only in dedicated workers. A SharedWorker can route messages, but a dedicated worker in one tab still has to own the file.

Fix 3: readwrite-unsafe, in Chromium only

Chrome 121 added createSyncAccessHandle({ mode: "readwrite-unsafe" }), which lets several handles write to the same file. It removes the error, not the problem: two tabs writing the same bytes still overwrite each other, and the Chrome team's announcement says you need your own locking. Because Firefox and Safari ignore it, only use it as an optimisation behind supportsLockModes(), with Fix 1 or Fix 2 as the fallback.

If your other tabs only need to read, you don't need any of this. fileHandle.getFile() returns a snapshot of the file without taking a lock, and worked in all three browsers while another tab held the file open.

What about SQLite WASM?

SQLite in the browser keeps its database in OPFS, so it hits the same lock. According to the SQLite WASM persistence docs:

  • opfs-sahpool is the fastest and needs no special headers, but only one connection can be open at a time. A second tab fails.
  • opfs works across tabs, but needs the COOP and COEP headers because it uses SharedArrayBuffer, and it's slower.

A common setup is opfs-sahpool inside the leader tab's worker from Fix 2, with the other tabs sending it queries. It's fast, works without special headers, and works in every browser.

Try it in your browser

Open this page in two tabs. Click Hold the file in one, then Try to open in the other to see your browser's error. Open with a Web Lock waits for the lock instead, and succeeds as soon as you release it in the first tab.

Results appear here. The test uses one empty file in this site's private storage. Nothing leaves your device.

Practical rules

  • Assume your app is open in more than one tab. Users open links in new tabs all the time, and restored sessions open several at once.
  • Never open a sync access handle without a plan for the second tab: a Web Lock, a leader tab, or getFile() for reads.
  • Catch both error names, NoModificationAllowedError and InvalidStateError, or Safari users get a different bug from everyone else.
  • Don't trust the mode option without checking for it. It's silently ignored outside Chromium.
  • Close handles in a finally block. A leaked handle keeps the file locked until the tab closes.
  • Test with two real tabs in Chrome, Firefox and Safari before you ship. Single-tab tests won't show any of this.

FAQ

Why does OPFS throw NoModificationAllowedError?

Because another tab, worker or stream already has the file open. createSyncAccessHandle() takes an exclusive lock on the file by default, so a second open fails until the first handle is closed. This is by design in the File System standard, not a browser bug, and it was still the default in Chrome, Firefox and Safari in November 2026.

Why does Safari throw InvalidStateError instead of NoModificationAllowedError?

WebKit, the engine behind Safari, reports the same lock conflict as InvalidStateError. In my tests Chrome and Firefox threw NoModificationAllowedError, while WebKit threw InvalidStateError for the same situation. Code that only checks for NoModificationAllowedError will miss the error in Safari, so check for both.

Does readwrite-unsafe work in Firefox and Safari?

No. As of November 2026 only Chromium browsers (Chrome 121 and later, Edge and others) support the mode option of createSyncAccessHandle. Firefox and Safari ignore it without an error and return a normal exclusive handle, so the second tab still fails. In my tests that was true for read-only mode too.

Can two tabs read the same OPFS file at the same time?

Yes, with fileHandle.getFile(). It returns a snapshot of the file and doesn't need a lock, and it worked in Chrome, Firefox and Safari's engine while another tab held the file open. Opening a second sync access handle, even in read-only mode, only works in Chromium.

Is the OPFS lock released when a tab is closed?

Yes. In my tests closing a tab that held a sync access handle released the lock in Chrome, Firefox and Safari's engine, and another tab could open the file straight away. A handle you forget to close inside a tab that stays open keeps the file locked until that tab closes or reloads.

Can I open OPFS files from a SharedWorker?

Not with createSyncAccessHandle in Chrome and Firefox: it only exists in dedicated workers. A SharedWorker can coordinate the tabs, but the file itself has to be opened by a dedicated worker in one of them. The leader-tab pattern does that with the Web Locks API.

Does SQLite WASM have the same multi-tab problem?

Yes, because it stores the database in OPFS. The opfs-sahpool VFS keeps the file open and allows one connection at a time, so a second tab fails. The opfs VFS supports several tabs but needs COOP and COEP headers. Many apps run SQLite in one leader tab and send queries to it from the others.

How I tested

  • Chromium 159, Firefox 159 and WebKit 27.2, driven by Playwright on an M1 MacBook Air, with a persistent profile so storage behaved like a normal browser window.
  • WebKit is the engine Safari uses, but it isn't the exact Safari build you download, so confirm critical behaviour in real Safari on macOS and iOS.
  • Each "tab" was a separate page in the same profile, using its own dedicated worker, which is how a real user's tabs behave.
  • The failure counts are the median of five runs. The exact numbers depend on timing; the point is that every browser fails often without a lock, and none failed with one.