Skip to content

Commit 1ec737f

Browse files
authored
fix(auth-js): replace Math.random with crypto based UUID to support Next.js 16 SSR
Next.js 16 App Router requires deterministic rendering for Server Components. The previous implementation of uuid() in @supabase/auth-js used Math.random(), which caused prerender errors even when no queries were executed. This update replaces Math.random() with crypto.getRandomValues in browsers and crypto.randomFillSync in Node, providing SSR-safe, fully synchronous UUID v4 generation. ### Changes - Refactored uuid() in packages/auth-js/src/lib/helpers.ts - Fully synchronous and UUID v4 compliant - Compatible with Node 16+ and modern browsers - Resolves SSR/deterministic rendering errors caused by Math.random() Closes #40273
1 parent d1ba7d9 commit 1ec737f

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

packages/core/auth-js/src/lib/helpers.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,24 @@ export function expiresAt(expiresIn: number) {
99
return timeNow + expiresIn
1010
}
1111

12-
export function uuid() {
13-
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
14-
const r = (Math.random() * 16) | 0,
15-
v = c == 'x' ? r : (r & 0x3) | 0x8
16-
return v.toString(16)
17-
})
12+
export function uuid(): string {
13+
const bytes = new Uint8Array(16)
14+
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
15+
crypto.getRandomValues(bytes)
16+
} else {
17+
const cryptoNode = require('crypto')
18+
cryptoNode.randomFillSync(bytes)
19+
}
20+
bytes[6] = (bytes[6] & 0x0f) | 0x40
21+
bytes[8] = (bytes[8] & 0x3f) | 0x80
22+
23+
let i = 0
24+
return bytes.reduce((uuid, byte) => {
25+
const hex = byte.toString(16).padStart(2, '0')
26+
if (i === 4 || i === 6 || i === 8 || i === 10) uuid += '-'
27+
i++
28+
return uuid + hex
29+
}, '')
1830
}
1931

2032
export const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'

0 commit comments

Comments
 (0)