Dev Helpers

Node.js / Cryptographic primitives

Generate a fixed number of random bytes

Dev Helpers · July 9, 2026

Random byte counts describe entropy-bearing bytes, not the final string length. Hex and base64 encode the same bytes at different lengths.

Worked example

import {
  createHash,
  createHmac,
  randomUUID,
  randomBytes,
  timingSafeEqual,
  generateKeyPairSync,
  sign,
  verify,
  createSecretKey,
} from "node:crypto";
console.log(randomBytes(16).length);

Result

16

Implementation notes

Returning random data as text requires a defined encoding. Consumers should know whether a displayed length is a byte count or a character count.

Try it yourself

Generate 16 bytes and compare both encodings.

Open the Node.js example →

Editorial date July 9, 2026 · Published December 6, 2026

Related articles

Safely parse malformed input

Parsing user-provided JSON needs a failure path. Successful parsing alone does not establish that the result has the expected shape.

Checksum bytes with CRC32

CRC32 is useful for detecting accidental changes to a byte sequence. Record the input encoding so different producers compute the same checksum.

Attach details to a mark

Performance marks can carry details about the operation they describe. Small stable identifiers are easier to aggregate than large payloads.