Skip to content

Commit 2397d80

Browse files
authored
Replace Math.random() with performance.now() in uuid() for pre-render builds in Next.js v16
Replace Math.random() with performance.now() in uuid() for pre-rendered caching in Next.js v16 Uses `performance.now()` as the primary entropy source, mixed with a counter and simple hashing. This is a replacement to using Math.random().
1 parent 5e6dda1 commit 2397d80

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

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

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,27 @@ 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+
// Use performance.now() as primary entropy source
14+
let counter = 0;
15+
let state = 0;
16+
17+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
18+
// Use performance timer if available
19+
const perf = typeof performance !== 'undefined' ?
20+
Math.floor(performance.now() * 1000000) : counter;
21+
22+
// Mix with counter using prime multiplication
23+
const entropy = (perf * 16807) ^ (++counter * 2654435761);
24+
25+
// Simple hash mixing
26+
state = (state * 1103515245 + 12345) ^ entropy;
27+
const r = (state >>> (counter % 28)) & 0xF;
28+
29+
// Apply UUID v4 rules
30+
const v = c == 'x' ? r : (r & 0x3) | 0x8;
31+
return v.toString(16);
32+
});
1833
}
1934

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

0 commit comments

Comments
 (0)