Mutual Exclusion With Web Locks
Serialize work across tabs with navigator.locks.request, so two tabs never write the same storage key at the same moment.
Code
async function withLock(name, task) {
return navigator.locks.request(name, { mode: 'exclusive' }, async () => {
console.log('lock acquired:', name);
try {
return await task();
} finally {
console.log('lock released:', name);
}
});
}
async function saveDraft(payload) {
await new Promise((resolve) => setTimeout(resolve, 30));
console.log('saved draft:', payload);
}
await Promise.all([
withLock('draft-write', () => saveDraft('tab-a')),
withLock('draft-write', () => saveDraft('tab-b')),
]);
console.log('both writes finished without overlap');Output
Captured from a sandboxed run of this snippet in the build pipeline.
lock acquired: draft-write
saved draft: tab-a
lock released: draft-write
lock acquired: draft-write
saved draft: tab-b
lock released: draft-write
both writes finished without overlapHow it works
Mutual Exclusion With Web Locks is built around the functions withLock and saveDraft.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Points of care
- The snippet leans on
navigator— browser-only surfaces a bare Node process cannot provide.
Putting it to use
The main signature, verbatim, is async function withLock(name, task)
Look for the lock acquired:, lock released:, saved draft: prefixes during the file’s run; they match each line of output to the step that emitted it.
Core lines
await new Promise((resolve) => setTimeout(resolve, 30));
return navigator.locks.request(name, { mode: 'exclusive' }, async () => {
console.log('lock acquired:', name);
try {
return await task();
} finally {
console.log('lock released:', name);
}
});
await Promise.all([
withLock('draft-write', () => saveDraft('tab-a')),
withLock('draft-write', () => saveDraft('tab-b')),
]);
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `withLock`, `saveDraft` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.