Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Web APIs in Node.js

Node.js crypto.getRandomValues() method

Reference for crypto.getRandomValues() in Node.js: fill an integer typed array with cryptographically secure random values, with the 65,536-byte limit.

crypto.getRandomValues(typedArray) fills an integer typed array in place with cryptographically secure random values and returns the same array. It is the Web Crypto way to get random bytes and is identical in browsers, so the same code works on the server and in the page.

The values come from the operating system's secure random generator, which makes them suitable for keys, tokens and nonces. Math.random() is not suitable for those.

NODE
const bytes = crypto.getRandomValues(new Uint8Array(16));

Try it

Node.js Filling different typed arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Limits and wrong types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
crypto.getRandomValues(typedArray)   // returns typedArray
Name Description
typedArray An Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array or BigUint64Array.

Returns: the same typed array, now filled with random values.

Errors: a QuotaExceededError (DOMException) when the array is larger than 65,536 bytes; a TypeMismatchError for floating-point arrays and for values that are not integer typed arrays, such as a plain array.

Usage notes

  • In place. The function overwrites the array you pass; it does not allocate a new one.
  • 65,536-byte limit per call. For larger buffers call it in a loop over subarray() slices, or use crypto.randomBytes() or crypto.randomFill().
  • Float arrays are rejected. Random floats need extra work and a clear idea of the distribution you want.
  • Do not reduce with a plain modulo to pick a number in a range: that skews the result. crypto.randomInt() does it without bias.
  • Synchronous and fast. It never blocks waiting for entropy on modern systems.
  • Global. No import needed. require('node:crypto').getRandomValues is the same function, and webcrypto.getRandomValues is available too.
  • Not seedable. If a test needs reproducible values, inject a fake source instead of calling this.