Node.js Reference ยท crypto
Node.js crypto.randomBytes() method
Reference for crypto.randomBytes() in Node.js: generate cryptographically secure random Buffers synchronously or with a callback, encode tokens and size keys.
crypto.randomBytes(size) returns a Buffer of size cryptographically secure random bytes. The data comes from the operating system's random generator, so it is suitable for secret keys, salts, initialization vectors, session IDs and password reset tokens. Math.random() is never a substitute.
Without a callback the call is synchronous and returns the buffer. With a callback the work is done on the thread pool and the result is passed to the callback. For ordinary sizes (tens of bytes) the synchronous form is fast enough and simpler.
import { randomBytes } from 'node:crypto'; const token = randomBytes(32).toString('hex');
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.randomBytes(size) // Buffer crypto.randomBytes(size, callback) // void; callback(err, buf)
| Name | Description |
|---|---|
size |
Number of bytes to generate: an integer from 0 up to 2**31 - 1. |
callback |
Optional (err, buf) => {}. When given, the function returns undefined. |
Returns: a Buffer of the requested length (synchronous form).
Errors: a size that is not a number throws ERR_INVALID_ARG_TYPE; a negative or too large size throws ERR_OUT_OF_RANGE. In the callback form these errors are still thrown synchronously, not passed to the callback.
Usage notes
- Size tokens in bytes of entropy, not characters. 16 bytes is 128 bits, a sound minimum for unguessable IDs; 32 bytes (256 bits) is a comfortable default for secrets.
- Encode for transport.
'hex'doubles the length;'base64url'is shorter and safe in URLs and file names. - Do not turn bytes into numbers with
%. Takingbuf[0] % 10is biased. For integers in a range usecrypto.randomInt(). - Large sizes block the thread in the synchronous form while the OS generates them. For megabytes use the callback form or fill an existing buffer with
crypto.randomFill(). - The sync form never blocks waiting for entropy on modern operating systems; the generator is seeded at boot.
- It is not seedable. For reproducible test data use a seeded pseudo-random generator you write yourself, and never in production secrets.
- Same quality as
crypto.getRandomValues()andcrypto.randomUUID(); choose by the shape you need.