No, Math.random() is not secure: MDN states plainly that it does not provide cryptographically secure random numbers and must not be used for anything security-related. For tokens, passwords, session IDs and keys, use crypto.getRandomValues() or crypto.randomUUID() in the browser, crypto.randomBytes() or crypto.randomInt() in Node.js, and the secrets module in Python.
Why Math.random() is not secure
Math.random() returns a float between 0 (inclusive) and 1 (exclusive) from a fast pseudo-random number generator (PRNG). A PRNG is a formula: given its internal state, every future output is fixed. If an attacker can work out that state, they can predict the next values your code will generate.
V8, the engine in Chrome, Edge and Node.js, has used an algorithm called xorshift128+ since 2015. The V8 team's own post announcing the switch describes its 128 bits of internal state and says the algorithm "is still not cryptographically secure", pointing to crypto.getRandomValues for anything that needs security.
The practical risk is not that a single number looks non-random. It is that a run of outputs leaks enough about the generator's state to predict the rest. A password reset token, an invite code or a "secret" URL built from Math.random() can be guessed by someone who has collected enough of your other outputs.
Math.random vs crypto.getRandomValues at a glance
Math.random() | crypto.getRandomValues() | |
|---|---|---|
| Output | One float in [0, 1) | Fills an integer typed array in place |
| Predictable if the state is known | Yes | No (cryptographically secure generator) |
| Seedable | No | No |
| Size limit per call | n/a | 65,536 bytes |
| Use for | Games, animations, shuffling a UI list, simulations | Tokens, passwords, IDs, nonces, salts, anything an attacker would like to guess |
Secure random numbers in the browser
crypto.getRandomValues() fills an integer typed array with random values and returns the same array:
const bytes = crypto.getRandomValues(new Uint8Array(16));
const words = crypto.getRandomValues(new Uint32Array(2));
Rules from MDN worth knowing before you hit them:
- It only accepts integer arrays (
Uint8Array,Int32Array,BigUint64Arrayand so on), notFloat32ArrayorFloat64Array. Passing a float array throwsTypeMismatchError; in Node.js 18 the message isThe data argument must be an integer-type TypedArray. - One call can fill at most 65,536 bytes. Asking for more throws
QuotaExceededError, which Node.js 18 words asThe requested length exceeds 65,536 bytes. - It is the only member of
Cryptothat also works on plainhttp://pages, and it works in Web Workers.
For a unique ID, crypto.randomUUID() returns a 36-character version 4 UUID built from a cryptographically secure generator, for example cac7d52f-ed43-4747-8d39-f5d65b091cca. Unlike getRandomValues, MDN lists it as available only in secure contexts (HTTPS or localhost). The larely UUID generator creates v4 UUIDs this way in your browser.
A secure random integer in a range (without modulo bias)
The common Math.floor(Math.random() * 6) + 1 dice roll has no secure one-line equivalent. The obvious translation, bytes[0] % 6, is slightly biased: a byte has 256 possible values, and 256 is not a multiple of 6, so some results come up more often. You can check the size of the effect for a range of 100 yourself: mapping all 256 byte values with % 100 produces 0 through 55 three times each and 56 through 99 only twice each.
The fix is rejection sampling: throw away the few raw values at the top that would cause the imbalance and draw again.
// Returns an integer n with min <= n < max, uniformly distributed.
function secureRandomInt(min, max) {
const range = max - min;
if (!Number.isInteger(range) || range <= 0 || range > 2 ** 32) {
throw new RangeError("range must be an integer between 1 and 2^32");
}
// Largest multiple of range that fits in 32 bits; values at or above it are rejected.
const limit = 2 ** 32 - (2 ** 32 % range);
const buf = new Uint32Array(1);
do {
crypto.getRandomValues(buf);
} while (buf[0] >= limit);
return min + (buf[0] % range);
}
secureRandomInt(1, 7); // a die roll, 1 to 6
For a die roll the limit is 4,294,967,292, so only 4 of the 4,294,967,296 possible 32-bit values are ever rejected and the loop almost never repeats. Running it 600,000 times in Node.js 18 gave counts between 99,635 and 100,533 for each face, which is the spread you'd expect from a fair die.
A random token (URL-safe)
For reset links, API keys and invite codes, generate random bytes and encode them. 32 bytes gives 256 bits, the amount Python's secrets documentation describes as believed sufficient for typical use (as of 2015, the date it gives):
function randomToken(bytes = 32) {
const buf = crypto.getRandomValues(new Uint8Array(bytes));
return btoa(String.fromCharCode(...buf))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
randomToken(); // e.g. "59WpmmI6A4PHxgkDLu4GU4rK1Mbr1BOt8Xcf4ZfgKqA" (43 characters)
The replace calls turn standard base64 into the URL-safe alphabet and drop the padding. Never pad a token with characters chosen by Math.random() "for extra randomness"; that only adds a predictable part.
Node.js: crypto.randomBytes, randomInt and randomUUID
const { randomBytes, randomInt, randomUUID } = require("node:crypto");
randomBytes(32).toString("hex"); // 64 hex characters
randomInt(1, 7); // 1 to 6
randomUUID(); // version 4 UUID
The Node.js docs describe randomBytes as generating "cryptographically strong pseudorandom data", say randomInt returns an integer with min <= n < max and "avoids modulo bias", and note that the range must be less than 248. So in Node you don't need the helper above.
The browser-style global crypto needs care on old Node versions. It became available without a flag in Node.js 19.0.0. On Node.js 18, a script that calls crypto.getRandomValues(...) fails with ReferenceError: crypto is not defined (it only appears to work in the REPL and node -e, where built-in modules are preloaded as globals). Import it explicitly instead: import { webcrypto } from "node:crypto", then call webcrypto.getRandomValues(...).
Python: secrets, not random
Python has the same split. The random module uses the Mersenne Twister, and its documentation warns that its generators "should not be used for security purposes". Use secrets:
import secrets
secrets.token_urlsafe(32) # URL-safe text token from 32 random bytes
secrets.token_hex(16) # 32 hex characters
secrets.randbelow(6) + 1 # die roll, 1 to 6
secrets.choice("abcdef0123456789")
The secrets docs say it should be used "in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography."
When Math.random() is fine
Use it when nobody gains anything by predicting the value: particle effects, a random background colour, picking which tip to show, test data for a demo, Monte Carlo simulations. If you need the same sequence twice (a reproducible game level or test), Math.random() can't do that either, because it can't be seeded; use a seeded PRNG library for that job.
A quick rule: if the value is ever compared against something a user submits (a token, a code, a password) or controls access to anything, it needs a cryptographic generator. To see how much randomness a password needs, read password entropy explained; to generate one now, the larely password generator uses crypto.getRandomValues in your browser.
Frequently asked questions
- Is crypto.getRandomValues truly random?
- No, and it doesn't need to be. MDN explains that browsers use a pseudo-random number generator seeded with enough entropy, and that the algorithm may vary between browsers but is suitable for cryptographic purposes. What matters for security is that the output cannot be predicted, which a properly seeded cryptographic generator provides.
- Is crypto.getRandomValues slower than Math.random?
- It does more work per value, but for generating tokens, IDs and passwords the difference is irrelevant: you need a few dozen bytes, not millions of numbers per second. Keep Math.random for animations, games and simulations where speed matters and predictability does not.
- Can I seed Math.random to get repeatable results?
- No. JavaScript gives you no way to seed Math.random. If you need a repeatable sequence for tests or procedural generation, use a small seeded PRNG library or write one, and never use that for anything security-related.
- Is crypto.randomUUID safe to use as a session ID or reset token?
- A version 4 UUID from crypto.randomUUID comes from a cryptographically secure generator, so it is unpredictable. For secrets like reset tokens, many developers still prefer 32 random bytes encoded as base64url, which gives 256 bits and is what Python's secrets documentation suggests as sufficient for typical use.
Sources
- MDN: Math.random()
- MDN: Crypto.getRandomValues()
- MDN: Crypto.randomUUID()
- V8 blog: There's Math.random(), and then there's Math.random()
- Node.js docs: Crypto (randomBytes, randomInt, randomUUID)
- Node.js docs: Globals (crypto)
- Python docs: secrets, generate secure random numbers
- Python docs: random, generate pseudo-random numbers