Skip to content

Topics

Jump to a topic.

Search questions

Find a question by title, tag, or summary.

Why shouldn't you use Math.random for tokens or IDs?

Questions in this chapter (8)
  • Draft
  • easy
  • Askedoften
  • Verified October 2026

Answer

Because Math.random is built to be fast and statistically uniform, not unpredictable.

The spec's whole requirement is a Number in [0, 1), "chosen randomly or pseudo randomly with approximately uniform distribution", using an implementation-defined algorithm, plus distinct sequences for distinct realms. It says nothing about seeding quality or predictability, so no security property can be relied on.

In practice engines use a small, fast pseudo-random generator. In V8 it's xorshift128+ (since V8 4.9, Chrome 49): 128 bits of state that pass statistical tests, but the V8 team states it "is still not cryptographically secure". Its output is a deterministic function of a small internal state, and it isn't designed to stop someone who has seen earlier outputs from working out that state and the values that follow. In V8 you can even see the determinism directly: the --random-seed flag fixes the seed and replays the same sequence.

That matters wherever a value must be unguessable: session IDs, password-reset and CSRF tokens, invite codes, API keys, one-time codes, nonces. Use a CSPRNG (cryptographically secure pseudo-random number generator) instead:

  • crypto.getRandomValues(typedArray) from the Web Crypto API fills an integer typed array (up to 65,536 bytes) with cryptographically strong values. It works in browsers, workers and Node.js.
  • crypto.randomUUID() returns a random version 4 UUID. In browsers it's limited to secure contexts (HTTPS).
  • In Node.js, crypto.randomInt(min, max) returns an integer in [min, max) without modulo bias, and crypto.randomBytes returns a Buffer.

Math.random remains fine for things that aren't secrets: shuffling a demo playlist, jitter in retry back-off, sampling, games without stakes.

Example

import { execFileSync } from 'node:child_process';

// Node.js 24 (V8): a fixed seed replays the exact same "random" numbers.
const run = () =>
  execFileSync(process.execPath, ['--random-seed=42', '-p', 'Math.random()']).toString();
console.log(run() === run()); // → true

// Unguessable values come from the CSPRNG.
const id = crypto.randomUUID();
console.log(id.length, id[14]); // → 36 4

const bytes = crypto.getRandomValues(new Uint8Array(32)); // 256 bits
const token = Buffer.from(bytes).toString('base64url'); // Buffer: Node.js only
console.log(token.length); // → 43

try {
  crypto.getRandomValues(new Uint8Array(65537));
} catch (error) {
  console.log(error.name); // → QuotaExceededError
}

Pitfalls

  • Building IDs as Math.random().toString(36).slice(2). However long the string looks, it's derived from a predictable generator.
  • Mapping random bytes to a range with %. byte % 6 over 256 values is biased toward the low results; use crypto.randomInt or reject values above the largest multiple of the range.
  • Assuming a UUID is a secret just because it's random. A v4 UUID has 122 random bits, enough to be unguessable, but it's often logged or exposed in URLs; treat tokens as credentials.
  • Calling crypto.randomUUID() on a plain-HTTP page. It's marked [SecureContext], so the method doesn't exist there; getRandomValues isn't restricted.

Follow-ups

Isn't xorshift128+ "good randomness"?
Statistically, yes: V8 chose it because it passes the TestU01 suite, which the older MWC1616 failed. Statistical quality and unpredictability are different properties; a CSPRNG must also resist an attacker who has seen previous outputs.
Is crypto.getRandomValues slower?
Per call, yes: the V8 team describes it as cryptographically secure "at a performance cost". For tokens that cost is negligible, since you generate a few bytes per request, not millions of floats in a loop.
Can you seed Math.random for reproducible tests?
Not from JavaScript; the language has no seeding API. In V8 the --random-seed flag does it for the whole process. For reproducible tests, use a small seeded PRNG you control and inject it.

Exercises

Spot the bias

const roll = () => (crypto.getRandomValues(new Uint8Array(1))[0] % 6) + 1;

Comments

Comments are GitHub Discussions: you sign in with GitHub to post or react.