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): Uint8ArrayParameters
| Parameter | Type | Description |
|---|---|---|
size | number (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.getRandomValueswhen available for secure randomness, and falls back toMath.randomif not. - If
crypto.getRandomValuesis available (supported environments include browser and Node.js), it is used for cryptographically secure random number generation. - In environments where
crypto.getRandomValuesis not available, the function falls back toMath.random, which is not cryptographically secure. - If
sizeis 0 or negative, an emptyUint8Arrayis 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)
