Web Locks API Guide: Coordinating Access to Shared Resources Across Browser Tabs

How to use the Web Locks API to coordinate access to shared resources like IndexedDB across multiple tabs of the same site, avoiding concurrent writes and race conditions.

Web Locks API Guide: Coordinating Access to Shared Resources Across Browser Tabs

If you have ever opened the same website in two different browser tabs and noticed something odd — duplicated data, overlapping sync jobs, a counter that "jumps" — you have probably run into a cross-tab concurrency problem. When several windows or tabs of the same site run JavaScript in parallel, they can end up reading or writing the same shared resource at the same time, such as an IndexedDB database or a local cache, with unpredictable results.

Modern browsers solve exactly this kind of problem with the Web Locks API, a JavaScript interface designed to coordinate access to shared resources across tabs, windows and web workers of the same origin (the same site). In this guide we'll look at what it is, how it works, and how to use it with practical examples.

What the Web Locks API is

The Web Locks API introduces the concept of a lock: an exclusive, or shared, permission on a resource identified by a name the developer chooses freely. The entry point of the API is the navigator.locks object, available both in regular web pages and in web workers via WorkerNavigator.locks.

The core idea is simple: before performing a sensitive operation on a shared resource, a tab "requests" a lock with a given name. If no other tab is already using it, the lock is granted immediately and the code can proceed safely. If another tab already holds it, the request is automatically queued and fulfilled as soon as the lock becomes free.

One important detail: locks are only valid within the same origin (protocol, domain and port). Two different sites can never interfere with each other, even if they happened to choose the same lock name.

Core concepts: name, mode and queue

To use the API effectively, it helps to know a few key concepts.

  • Resource name: an arbitrary string, chosen by the developer, that identifies the lock. All requests using the same name compete for the same lock.
  • Exclusive mode ("exclusive"): the default mode. Only one requester at a time can hold the lock; it's meant for write operations.
  • Shared mode ("shared"): multiple requesters can hold a lock with "shared" mode at the same time, but no one can obtain an "exclusive" version while any shared ones are active. This is the classic readers-writer pattern: many reads in parallel, but only one write at a time.
  • Request queue: if a lock is already held, new requests for the same name are queued and granted in order, with no need to manually implement waiting logic with setTimeout or polling.
  • Automatic release: a lock is never released manually. It is released automatically when the function it was granted to finishes, whether by normal completion or by throwing.

Basic syntax: navigator.locks.request()

The API's main method is navigator.locks.request(), which takes a resource name, an optional options object, and a callback function:

navigator.locks.request("user_data_sync", async (lock) => {
  // This code only runs once the lock has been granted.
  // No other tab can run this same block until we return here.
  await syncWithIndexedDb();
});

The callback receives a Lock object as its argument, exposing the name and mode of the granted lock. The call returns a Promise that resolves with the value returned by the callback, once the lock has been released: this makes it natural to use await to wait for the whole operation to complete.

The most useful options you can pass as the second argument are:

  • mode: "exclusive" (default) or "shared".
  • ifAvailable: if set to true, the request is never queued; if the lock isn't free, the callback is called immediately with null instead of a lock.
  • signal: an AbortSignal (produced by an AbortController) that lets you cancel a still-queued request, useful for implementing a maximum wait timeout.
  • steal: forces the release of a lock already held by other code so it can be granted immediately to the new request, bypassing the queue. It must be used with great caution, because the code that held the lock is not interrupted: it keeps running and may conflict with whoever "stole" it.

Practical example: avoiding concurrent writes to IndexedDB

Imagine a web app that keeps a local cache in IndexedDB and periodically synchronizes it with a server. If the user has three tabs open on the same site, without precautions all three could start the sync at the same moment, writing duplicated or conflicting data.

The Web Locks API solves this with a pattern known as leader election: every tab tries to acquire the same lock with the ifAvailable option, but only one will actually succeed; the others, finding the lock already held, simply skip the operation.

async function syncIfNotAlreadyRunning() {
  await navigator.locks.request(
    "indexeddb_cache_sync",
    { ifAvailable: true },
    async (lock) => {
      if (!lock) {
        // Another tab is already syncing: do nothing.
        console.log("Sync already running in another tab.");
        return;
      }

      console.log("Starting sync from this tab.");
      const serverData = await fetch("/api/latest-data").then(r => r.json());
      await writeToIndexedDb(serverData);
    }
  );
}

This way, no matter how many tabs are open, the actual sync happens in only one of them at a time, with no need for server-side coordination or external libraries.

Readers and writers: the shared mode

Another very common scenario is one where many read-only operations can safely happen in parallel, but a write needs exclusive access. The "shared" mode is designed exactly for this:

async function readData() {
  return navigator.locks.request(
    "products_cache",
    { mode: "shared" },
    async () => {
      return readFromIndexedDb();
    }
  );
}

async function updateData(newData) {
  return navigator.locks.request(
    "products_cache",
    { mode: "exclusive" }, // default value, made explicit for clarity
    async () => {
      return writeToIndexedDb(newData);
    }
  );
}

Multiple calls to readData(), even from different tabs, can proceed at the same time. When an updateData() request comes in, however, it waits for all ongoing reads to finish, acquires the lock exclusively, and only after it completes can new reads (or writes) resume.

Handling timeouts with AbortSignal

By default, a lock request stuck in the queue can wait indefinitely if whoever holds it never releases it, for example because of a bug. To avoid leaving the interface stuck waiting, it's good practice to set a maximum timeout using AbortController:

async function syncWithTimeout() {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 3000); // wait at most 3 seconds

  try {
    await navigator.locks.request(
      "indexeddb_cache_sync",
      { signal: controller.signal },
      async () => {
        await syncWithIndexedDb();
      }
    );
  } catch (error) {
    if (error.name === "AbortError") {
      console.warn("Timeout: the lock was not granted in time.");
    } else {
      throw error;
    }
  } finally {
    clearTimeout(timeoutId);
  }
}

Diagnosing active locks with navigator.locks.query()

When something isn't behaving as expected, it can be useful to inspect the current state of the lock manager. The navigator.locks.query() method returns a snapshot of all currently held and pending locks, including their name and mode. It's a tool meant mainly for debugging during development, not for application logic.

Watch out for deadlocks

As with any locking system, there is a risk of deadlock: a situation where two requests block each other permanently. A typical case: tab A holds the lock "resource-1" and, while holding it, also requests "resource-2"; at the same time tab B holds "resource-2" and requests "resource-1". Neither request can ever be fulfilled.

To avoid this scenario, some good practices:

  • Avoid nesting requests for different locks inside the same callback whenever possible.
  • If you really need to request multiple locks, always acquire them in the same order throughout the application's code.
  • Always use a signal with a timeout for critical operations, so that a potential deadlock resolves into a manageable error instead of a permanent freeze.

It's worth noting that a deadlock on Web Locks does not freeze the browser or other tabs: it stays confined to the code that depends on those specific locks.

Browser support

The Web Locks API is now considered Baseline: Widely Available since March 2022, meaning it is stably supported by all major browsers. Specifically, it is available from:

  • Google Chrome: starting with version 69.
  • Microsoft Edge: starting with version 79 (the first Chromium-based version).
  • Mozilla Firefox: starting with version 96.
  • Safari (desktop and iOS): starting with version 15.4.
  • Opera: starting with version 56.

An important requirement to keep in mind: the API only works in a secure context, meaning pages served over HTTPS (or on localhost during development). It is not available on unencrypted HTTP pages.

Conclusion

The Web Locks API elegantly and natively solves a problem that, before its introduction, required often fragile homemade solutions, such as using localStorage as an improvised "traffic light" between tabs. With navigator.locks.request(), you can implement robust patterns in just a few lines, such as leader election for synchronization, or a readers-writer scheme to protect access to a shared IndexedDB cache. Being a widely supported API available without any external libraries, it's one of the first things worth considering whenever a multi-tab web app needs to safely manage shared resources.

Sources

Share

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0