Random numbers in the browser: when Math.random is fine and when it is not
Every browser gives you a random number function. Math.random returns a float between 0 and 1, and it is fast and easy to use. It is also unsafe wherever an attacker could profit from predicting the next value, and confusing the two cases is a common front-end security mistake.
Two kinds of randomness
Math.random is a pseudorandom generator. The JavaScript specification does not require it to be cryptographically secure, and engines have used generators whose internal state can be recovered from a few outputs. That is fine for a shuffled playlist or a dice roll in a board game. It is not fine for a password, a reset token or a session identifier.
For those cases, use crypto.getRandomValues. It fills a typed array with bytes from the operating system's entropy source, and it is designed to resist prediction. crypto.randomUUID is built on the same source and returns a version 4 UUID.
Getting a number in a range without bias
A common shortcut is to take a random 32-bit value and use the remainder when dividing by six to get a die roll. That shortcut is biased. 2 to the power of 32 is not a multiple of six, so the values from 0 to 3 come up slightly more often than the others. The fix is rejection sampling: discard any value above the largest multiple of the range, then take the remainder of what is left. The bias is small, but in a raffle it can be measured.
Generating numbers yourself
The random number generator uses the browser's secure source for its output and runs entirely on your machine, so nothing is sent to a server. If you need raw bytes rather than decimal numbers, for example for a key or a salt, the random bytes generator returns them in hex or Base64.
What to pick
- A game, a shuffle, a visual effect: Math.random is enough.
- A lottery, a draw or a fair assignment: use a secure source with rejection sampling.
- A password, token, key or salt: always use a secure source, never Math.random.
Creator of TextArray — building free, privacy-first tools that run entirely in your browser.