crypto.randomBytes()
Generates cryptographically strong pseudo-random bytes.
Syntax
crypto.randomBytes(size[, callback]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
size | number | Yes | The number of bytes to generate. |
callback | function | No | Optional `(err, buf)` callback for async generation. |
Returns
Buffer — A Buffer of random bytes (sync form).
Examples
import { randomBytes } from 'node:crypto';
const token = randomBytes(32).toString('hex');
console.log(token.length);
Output
64
import { randomBytes } from 'node:crypto';
const session = randomBytes(24).toString('base64url');
console.log(session);
Output
kR3p-9fL2xQ7vN1mZ8aB4cD6
Notes
Use for session tokens, password reset codes, and salts; never use
`Math.random()` for security. Generating large amounts synchronously
blocks the event loop; pass a callback (or use `randomFill`) for big
sizes.