Skip to content

Commit 9a6edb9

Browse files
authored
fix: use JSON-based deep clone instead of structuredClone (#1084)
Not all JS runtimes support `structuredClone` (introduced in #1023). (Example: supabase/supabase-js#1504) - As the session data is safe to JSON serialize, replace `structuredClone` use with JSON de/serialize. - Added the helper function to increase the readability (making the intent clear).
1 parent c6cee20 commit 9a6edb9

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/GoTrueClient.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ import type {
112112
Web3Credentials,
113113
} from './lib/types'
114114
import { stringToUint8Array, bytesToBase64URL } from './lib/base64url'
115+
import { deepClone } from './lib/helpers'
115116

116117
polyfillGlobalThis() // Make "globalThis" available
117118

@@ -2419,13 +2420,13 @@ export default class GoTrueClient {
24192420
const mainSessionData: Omit<Session, 'user'> & { user?: User } = { ...sessionToProcess }
24202421
delete mainSessionData.user // Remove user (real or proxy) before cloning for main storage
24212422

2422-
const clonedMainSessionData = structuredClone(mainSessionData)
2423+
const clonedMainSessionData = deepClone(mainSessionData)
24232424
await setItemAsync(this.storage, this.storageKey, clonedMainSessionData)
24242425
} else {
24252426
// No userStorage is configured.
24262427
// In this case, session.user should ideally not be a proxy.
24272428
// If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here
2428-
const clonedSession = structuredClone(sessionToProcess) // sessionToProcess still has its original user property
2429+
const clonedSession = deepClone(sessionToProcess) // sessionToProcess still has its original user property
24292430
await setItemAsync(this.storage, this.storageKey, clonedSession)
24302431
}
24312432
}

src/lib/helpers.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,3 +405,11 @@ export function userNotAvailableProxy(): User {
405405
},
406406
})
407407
}
408+
409+
/**
410+
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
411+
* Note: Only works for JSON-safe data.
412+
*/
413+
export function deepClone<T>(obj: T): T {
414+
return JSON.parse(JSON.stringify(obj))
415+
}

0 commit comments

Comments
 (0)