Home / patterns

Tokens and IDs generated with Math.random()

Quick answer: Vibe-coded apps often build password reset tokens, invite codes, API keys or session IDs with Math.random() or Date.now(). MDN says Math.random() does not provide cryptographically secure random numbers and shouldn't be used for anything security-related, so these values can be guessed or predicted.

Last updated November 11, 2026

Steps

  1. Search the codebase for Math.random(, Date.now() used in IDs or tokens, and homemade generators like Math.random().toString(36).
  2. For anything that grants access (reset links, magic links, invite codes, API keys, session IDs, file share links), switch to crypto.randomBytes(32).toString('hex'), crypto.randomUUID() or crypto.randomInt() in Node, or crypto.getRandomValues() in the browser.
  3. Use at least 128 bits of randomness for tokens, store only a hash of long-lived tokens, and give reset or invite tokens a short expiry and single use.
  4. Invalidate tokens already issued by the old generator: expire open reset links and invites, and rotate API keys.
  5. Leave Math.random() for things that don't matter for security, like shuffling a UI list.

Why it matters

MDN states that Math.random() does not provide cryptographically secure random numbers and points to the Web Crypto API's getRandomValues() instead. The OWASP Cryptographic Storage Cheat Sheet says pseudo-random generators must not be used for security-critical values such as session IDs, CSRF tokens or password reset tokens, and lists Math.random() as unsafe in Node.js, recommending crypto.randomBytes(), crypto.randomInt() and crypto.randomUUID(). MITRE tracks this as CWE-338, Use of Cryptographically Weak PRNG.

Sources

MDN Web Docs: Math.random() — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

OWASP Cheat Sheet Series: Cryptographic Storage Cheat Sheet (Secure Random Number Generation) — https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html

Node.js documentation: Crypto (randomBytes, randomInt, randomUUID) — https://nodejs.org/api/crypto.html

MITRE CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator — https://cwe.mitre.org/data/definitions/338.html

Related patterns

Found a problem you'd rather not fix yourself?

Tell us what's wrong. A StorenTech engineer reviews your app and replies with a fixed quote, so you know the cost before any work starts.

Get it fixed by StorenTech

Vibe Security Weekly

One email a week with new failure patterns and how to fix them.

By joining you agree we may email you this newsletter. See our privacy policy. Free. Unsubscribe anytime. We'll never sell your email.