Toolbox-XToolbox-X

Generate Random Bytes

Generates random bytes in the Uint8Array format.

randomBytes

The randomBytes function generates random bytes in the Uint8Array format.

Info

Does not rely on Node.js or Web APIs. Works on any JS engine

Function Signature

randomBytes(size?: number): Uint8Array

Parameters

ParameterTypeDescription
sizenumber (optional)The length of the byte array to generate. Default: 8

Return Value

Returns a Uint8Array of the specified size containing randomly generated bytes.

Example Usage

playground.ts

Use Cases

  • Generating cryptographic keys
  • Creating raw binary seeds/nonces
  • Preparing buffers for cryptographic operations
  • Creating unique binary payloads

Implementation Notes

  • It uses crypto.getRandomValues when available for secure randomness, and falls back to Math.random if not.
  • If crypto.getRandomValues is available (supported environments include browser and Node.js), it is used for cryptographically secure random number generation.
  • In environments where crypto.getRandomValues is not available, the function falls back to Math.random, which is not cryptographically secure.
  • If size is 0 or negative, an empty Uint8Array is returned.

See Also

  • randomHex - Generate cryptographically secure random hex strings
  • randomNumeric - Generate cryptographically secure random numeric strings
  • randomAlphaNumeric - Generate cryptographically secure random alphanumeric strings
  • randomID - Generate customizable random alphanumeric ID (cryptographically not secure)

Last updated: Tue, Jun 16, 2026 08:45:18PM (UTC)

On this page