The Web Locks API: One Tab Does the Work, the Rest Wait
A user opens your dashboard, then opens it again in a second tab, then leaves a third one parked on another monitor from yesterday. Their access token expires. All three tabs notice at roughly the same instant, and all three fire a refresh request against your auth endpoint. Two of them get back a rotated refresh token that the third has already invalidated, and now the user is staring at a login…
The Web Locks API simplifies handling concurrency in web applications by providing a single method to manage shared resources across multiple tabs or iframes. When a user opens a dashboard in different tabs, each tab may independently attempt to refresh an access token upon expiration. This leads to race conditions where two tabs try to refresh simultaneously, causing one to overwrite the other's work and forcing the user to log in again.
The Web Locks API addresses this issue by allowing only one tab to hold a lock for a specific resource name at a time, preventing overlapping operations. When a tab requests a lock with the name "token-refresh", it waits until the lock is available before proceeding. If another tab has already obtained the lock, the requesting tab is put on hold until the lock is released. Once the lock is released, the waiting tab takes control and completes the refresh operation.
The API supports various options to fine-tune the locking behavior. The "mode" option can be set to "shared" for reader-writer scenarios, allowing multiple tabs to hold the lock simultaneously for reading, while an exclusive holder blocks further readers. The "ifAvailable" option enables leader-election, where the first tab to acquire the lock becomes the leader, and the remaining tabs stand down, reducing the chances of duplicate operations.
The lock is automatically released when the callback function completes or throws an error, eliminating the need for manual unlock operations. This ensures that locks are properly managed and avoids leaked locks that could cause issues. The callback function is executed while the lock is held, ensuring that only one tab can execute the critical section of code at a time.
The Web Locks API provides a safer and more reliable alternative to traditional methods like localStorage flags or BroadcastChannel messages. By utilizing the API, developers can avoid the race condition pitfalls and simplify the synchronization of shared resources across tabs. The API is widely supported and easy to use, making it a valuable tool for improving the reliability and user experience of web applications that operate in a multi-tab environment.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.