Crypto

crypto.randomBytes()

Generates cryptographically strong random bytes. This example verifies length rather than printing secret material. Prefer the asynchronous form for large allocations in request handlers. Tested on Node.js 22.16.0. Example output (one line per entry): ["true 32"].

Formal Syntax & Structure

nodejs syntaxnodejs
crypto.randomBytes(size[, callback])

Parameters & Attributes

NameTypeDescription
sizenumberRequested byte count.
callbackFunctionError-first completion callback.

Return Value

Buffer | undefined

Buffer when synchronous, otherwise callback result.

Working Example

Example Snippetnodejs
import { randomBytes } from 'node:crypto';import { promisify } from 'node:util';const bytes = await promisify(randomBytes)(32);console.log(Buffer.isBuffer(bytes), bytes.length);
Node.js Reference