Skip to content

Commit

Permalink
feat: default to navigatorLock on browsers (#807)
Browse files Browse the repository at this point in the history
After having spent months of real-world testing on supabase.com, the
`navigatorLock` is enabled on browsers that support the [Navigator
LocksManager
API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API).

This makes sure that concurrent access to the storage in multiple tabs,
windows or promises is no longer possible, thus removing issues such as:

- Refreshing the session in parallel
- Saving inconsistent state to storage
  • Loading branch information
hf committed Dec 20, 2023
1 parent cd4ebee commit b717b1c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/GoTrueClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
import { localStorageAdapter, memoryLocalStorageAdapter } from './lib/local-storage'
import { polyfillGlobalThis } from './lib/polyfills'
import { version } from './lib/version'
import { LockAcquireTimeoutError } from './lib/locks'
import { LockAcquireTimeoutError, navigatorLock } from './lib/locks'

import type {
AuthChangeEvent,
Expand Down Expand Up @@ -204,6 +204,14 @@ export default class GoTrueClient {
this.detectSessionInUrl = settings.detectSessionInUrl
this.flowType = settings.flowType

if (settings.lock) {
this.lock = settings.lock
} else if (isBrowser() && globalThis?.navigator?.locks) {
this.lock = navigatorLock
} else {
this.lock = lockNoOp
}

this.mfa = {
verify: this._verify.bind(this),
enroll: this._enroll.bind(this),
Expand Down
7 changes: 5 additions & 2 deletions src/lib/locks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ export const internals = {
),
}

/**
* An error thrown when a lock cannot be acquired after some amount of time.
*
* Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.
*/
export abstract class LockAcquireTimeoutError extends Error {
public readonly isAcquireTimeout = true

Expand Down Expand Up @@ -43,8 +48,6 @@ export class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {}
* function. The lock waits for that promise to finish (with or without error),
* while the function will finally wait for the result anyway.
*
* @experimental
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
Expand Down

0 comments on commit b717b1c

Please sign in to comment.