Code
// Browser + Node.js ≥ 19 (globalThis.crypto = Web Crypto API)
const randomToken = (bytes = 32) => {
// Unter 128 Bit Entropie ist ein Token leichter zu erraten
if (!Number.isInteger(bytes) || bytes < 16 || bytes > 65536) {
throw new RangeError('bytes muss eine ganze Zahl zwischen 16 und 65536 sein');
}
const buf = crypto.getRandomValues(new Uint8Array(bytes));
// Base64url: sicher für URLs und Cookies, ohne Padding
let bin = '';
for (const b of buf) bin += String.fromCharCode(b);
return btoa(bin)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
};
console.log(randomToken()); // 256 Bit
console.log(randomToken(16)); // 128 Bit
q3V9x_Lk2Hc0sR-mT8bYpWn4ZfJ1aE6uDgKiOvN7cXw
Zp4Kc_9sQm2LwX1-tRb8Ew