Node.js Reference ยท crypto
Node.js crypto.randomInt() method
Reference for crypto.randomInt() in Node.js: unbiased cryptographically secure random integers in a range, sync and callback forms, limits and use cases.
crypto.randomInt([min,] max[, callback]) returns a cryptographically secure random integer n where min <= n < max. The upper bound is exclusive and min defaults to 0. The result is uniformly distributed: Node.js rejects values that would skew the distribution instead of using a biased modulo.
Use it wherever the number matters for security or fairness: one-time codes, picking a random item from a list without bias, shuffling, lottery draws. For games and visual effects Math.random() is fine and faster.
import { randomInt } from 'node:crypto'; const dice = randomInt(1, 7); // 1 to 6
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
crypto.randomInt(max) // number crypto.randomInt(min, max) // number crypto.randomInt([min, ]max, callback) // void; callback(err, n)
| Name | Description |
|---|---|
min |
Lowest possible result (inclusive). Default 0. Must be a safe integer. |
max |
Upper bound (exclusive). Must be a safe integer greater than min. |
callback |
Optional (err, n) => {}. When given, the work is asynchronous. |
Returns: a safe integer in [min, max) (synchronous form).
Errors: non-integer or non-safe-integer bounds throw ERR_INVALID_ARG_TYPE; max <= min or max - min >= 2**48 throws ERR_OUT_OF_RANGE.
Usage notes
maxis exclusive. For a die userandomInt(1, 7), notrandomInt(1, 6).- The range (
max - min) must be smaller than2**48. Larger ranges need your own composition of random bytes. - Unbiased by design.
randomBytes(1)[0] % 6over-represents small values;randomInt()does not. Use it for picking array elements:items[randomInt(items.length)]. - Pad codes as strings. A numeric code such as
42should become'000042'; keep it a string in storage and comparison. - Entropy of codes is small. A six-digit code has under 20 bits; it needs rate limiting and a short lifetime to be safe.
- Sync form is cheap. The callback form exists mainly for symmetry with other
cryptofunctions and offers little benefit for small ranges. - Not seedable, so tests should inject a stand-in generator rather than rely on a particular result.