Random numbers

suggest change

Generating random values in Node.js falls into two distinct categories:

  1. Pseudo-Random Number Generation (PRNG): Suitable for non-security tasks such as simulations, game mechanics, animations, and non-sensitive UI sampling.
  2. Cryptographically Secure Pseudo-Random Number Generation (CSPRNG): Mandatory for security-sensitive use cases such as session identifiers, authentication tokens, password reset codes, cryptographic salts, and API keys.

1. Cryptographically Secure Random Numbers (node:crypto)

Node.js includes the built-in node:crypto module, backed by OpenSSL's entropy pool or system OS entropy (/dev/urandom on Unix, BCryptGenRandom on Windows).

Generating Secure Integers with crypto.randomInt

crypto.randomInt([min, ]max) generates a uniform, cryptographically secure integer within [min, max) without modulo bias:

import { randomInt } from 'node:crypto';

// Random integer between 0 (inclusive) and 100 (exclusive)
const percentage = randomInt(100);

// Random 6-digit OTP code (between 100,000 and 1,000,000)
const otp = randomInt(100_000, 1_000_000);
console.log(`Your verification code is: ${otp}`);

// Rolling a six-sided die [1..6]
const dieRoll = randomInt(1, 7);
console.log(`Rolled: ${dieRoll}`);

Generating Random Bytes and Hex Tokens with crypto.randomBytes

crypto.randomBytes(size) generates raw binary buffers of cryptographically secure random bytes:

import { randomBytes } from 'node:crypto';

// Generate a 32-byte secure authentication token (64 hex characters)
const apiToken = randomBytes(32).toString('hex');
console.log('API Token:', apiToken);

// Generate a base64url-encoded token safe for query parameters and URLs
const urlToken = randomBytes(24).toString('base64url');
console.log('URL Token:', urlToken);

Generating Standard UUIDs with crypto.randomUUID

Node.js provides native RFC 4122 version 4 UUID generation:

import { randomUUID } from 'node:crypto';

const userId = randomUUID();
console.log('UUIDv4:', userId); // e.g. "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"

Standard Web Crypto API (crypto.getRandomValues)

Modern Node.js (v19+) supports the standard Web Crypto API globally:

const buffer = new Uint32Array(4);
crypto.getRandomValues(buffer);
console.log('Cryptographic random integers:', buffer);

2. Non-Cryptographic Random Numbers (Math.random())

Math.random() returns a pseudo-random floating-point number in the range [0, 1). In Google V8 (the engine powering Node.js), Math.random() uses the xorshift128+ PRNG algorithm. It is fast and deterministic, but completely predictable after observing previous outputs.

Warning: Never use Math.random() for passwords, encryption keys, tokens, session IDs, or financial transactions.

Basic Range Helper

// Returns a random float between min (inclusive) and max (exclusive)
function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

// Returns a random integer between min (inclusive) and max (inclusive)
function getRandomInt(min, max) {
  const minCeil = Math.ceil(min);
  const maxFloor = Math.floor(max);
  return Math.floor(Math.random() * (maxFloor - minCeil + 1)) + minCeil;
}

console.log(getRandomFloat(1.5, 4.5));
console.log(getRandomInt(1, 10));

Picking Random Array Elements and Shuffling

const colors = ['red', 'green', 'blue', 'yellow', 'purple'];

// Pick a single random item
function sample(array) {
  return array[Math.floor(Math.random() * array.length)];
}

// Fisher-Yates In-Place Array Shuffle
function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

console.log('Sampled color:', sample(colors));
console.log('Shuffled colors:', shuffle([...colors]));

3. Custom Alphanumeric Password/Token Generator

Combining crypto.randomInt with a predefined character set provides an unbiased, cryptographically secure token generator:

import { randomInt } from 'node:crypto';

function generateSecureString(length = 16, charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*') {
  let result = '';
  const charsetLength = charset.length;
  for (let i = 0; i < length; i++) {
    result += charset[randomInt(0, charsetLength)];
  }
  return result;
}

const securePassword = generateSecureString(20);
console.log('Secure Password:', securePassword);

4. Key Takeaways

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents