Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 133 ยท Security and Cryptography

Randomness and Identifiers

Generate secure randomness in Node.js with crypto.randomBytes, randomInt and randomUUID, know when Math.random is fine, seed repeatable generators, and build ULID and nanoid-style IDs.

Random numbers appear in surprisingly many places: shuffling a playlist, picking a test case, creating a session token, generating a password reset link, assigning an ID to a new record. The word "random" hides two very different needs. Sometimes you only want variety: the next quote of the day should not always be the same. Sometimes you need unpredictability: if an attacker can guess your next password reset token, they can take over an account.

JavaScript gives you two sources for these two needs. Math.random() is fast and good enough for variety. The node:crypto module gives you randomness from the operating system, which is designed to be unguessable. Using the wrong one is a classic security bug, and this lesson shows you how to pick, how to generate secure numbers, tokens and identifiers, and how to make random data repeatable for demos and tests.

Because random output differs on every run, the examples in this lesson never print the random values themselves. They print properties that are always true: lengths, formats, ranges and counts. That is also the right way to test random code.

Math.random: fine for variety, wrong for secrets

Math.random() returns a number from 0 (included) up to 1 (excluded). It uses a fast pseudo-random number generator (PRNG): an algorithm that produces a long sequence that looks random, but is completely determined by a hidden internal state. If an attacker sees a few outputs, they can often work out the state and predict every later number. That makes it unsuitable for tokens, passwords, keys or anything an attacker would benefit from guessing.

Use it for: shuffling for display, jitter on retry delays, picking an animation, sampling for logging. Never use it for: session IDs, API keys, password resets, one-time codes, lottery draws with money at stake.

Node.js Making ranges from Math.random

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.

The conversion Math.floor(Math.random() * count) + min is the standard idiom. Note that Math.round is wrong here: it gives the first and last values only half the chance of the others.

Secure randomness with node:crypto

The node:crypto module asks the operating system's cryptographically secure generator (CSPRNG): Linux getrandom, Windows BCryptGenRandom and so on. These collect real entropy from hardware events and are built so that past outputs tell you nothing about future ones. They are somewhat slower than Math.random, but still fast enough for nearly everything: millions of values per second.

The main tools:

Function Result
randomBytes(n) a Buffer with n random bytes
randomInt(min, max) a random integer in [min, max), without bias
randomUUID() a random UUID version 4 string
getRandomValues(array) fills a typed array (the Web Crypto way)
randomFill(buffer) fills an existing buffer
Node.js randomBytes, randomInt and randomUUID

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.

Look at randomInt(1, 7): the upper bound is exclusive, like slice. A call with one argument, randomInt(10), returns 0 to 9. The function takes care of modulo bias (see below), which a naive byte % 6 does not.

randomBytes(32) gives 256 bits of randomness, which is the standard size for session tokens, API keys and CSRF tokens. Encode it with hex (64 characters) or base64url (43 characters, safe in URLs) as you learned in Buffers and Hashing and HMAC.

Synchronous and asynchronous forms

randomBytes(n) without a callback is synchronous and usually takes microseconds. With a callback, or through node:crypto's promisified form, the work is done on the thread pool. For small sizes the synchronous call is simply fine. For very large buffers (megabytes), prefer the asynchronous form so the event loop stays free.

Node.js The callback form and promisify

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.

Web Crypto: crypto.getRandomValues and crypto.randomUUID

Node.js also exposes the browser API as a global crypto object. That makes code portable between the browser and the server. crypto.getRandomValues(typedArray) fills the array (up to 65,536 bytes at once) and crypto.randomUUID() needs no import.

Node.js The global crypto object

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.

The last call fails on purpose: the Web Crypto API limits one call to 65,536 bytes, and the error is a QuotaExceededError. Use randomBytes for bigger buffers.

Modulo bias: why not byte % n

A common home-made recipe is "take a random byte (0 to 255) and use % 6 to get a die roll". It is subtly wrong. 256 does not divide evenly by 6 (256 = 6 x 42 + 4), so the values 0 to 3 appear 43 times and 4 and 5 only 42 times. The difference is small for dice but gets large when the range is large relative to the source. This is modulo bias, and it matters for tokens built from a custom alphabet.

The cure is rejection sampling: throw away the values that would cause unevenness. We can count exactly to see the effect by running through all 256 possible bytes:

Node.js Modulo bias, counted exactly

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.

With % 6 the faces 0 to 3 are slightly favored. With rejection sampling (discard the bytes 252 to 255) all six faces appear exactly 42 times. crypto.randomInt does this for you, so prefer it over hand-made schemes. Below we use it to build a fair custom alphabet.

Generating readable tokens and codes

Different needs call for different formats. Always choose the format by who reads it. A machine token can be long and ugly. A code a person must type should avoid look-alike characters (0/O, 1/l/I) and be short, but then it needs protection through expiry and attempt limits, because its entropy is low.

Node.js A token generator with a custom alphabet

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.

Entropy in bits tells you how hard guessing is. 6 decimal digits give only about 20 bits: roughly a million possibilities, so a six-digit one-time code is only safe if you also limit the attempts (for example five tries, then the code is void) and make it expire after minutes. A 256-bit token cannot be guessed by anyone, ever.

UUIDs

A UUID (universally unique identifier) is a 128-bit number written as 36 characters (8-4-4-4-12 hex digits). Version 4 UUIDs, which randomUUID() makes, have 122 random bits, so collisions are practically impossible without any coordination: two servers can create IDs independently and never clash.

Remember what a UUID v4 is and is not:

  • It is a good identifier. It is unique, and it is created without asking a database.
  • It is not a secret by definition (the standard does not promise it). Node's implementation does use a secure source, but design your system so that knowing an ID does not grant access; check permissions separately.
  • It is a poor primary key in databases with clustered indexes (such as MySQL InnoDB): fully random keys scatter inserts across the index and hurt write performance. That is why time-ordered IDs exist.

Time-sortable IDs: ULID and friends

A ULID (Universally Unique Lexicographically Sortable Identifier) is 26 characters. The first 10 encode a millisecond timestamp, the last 16 are random. Because the time comes first, IDs created later sort after earlier ones, even as plain strings. That keeps database indexes tidy and lets you order records by ID. UUID version 7 follows the same idea in UUID format. Node.js has no built-in generator for either, but writing one is simple. We use Crockford's Base32 alphabet (no I, L, O or U).

The example accepts the time as a parameter, so the output is repeatable for the timestamp part.

Node.js A ULID generator

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.

Two things to know when you use time-based IDs. First, they leak the creation time, which is sometimes a privacy issue. Second, several IDs created in the same millisecond are only ordered by their random part; real ULID libraries add a "monotonic" mode that increments the random part to keep order. If strict ordering matters within a millisecond, use a database sequence instead.

nanoid-style short IDs

For URLs, short links and public identifiers, 36-character UUIDs are long. The popular nanoid package produces 21 characters from a 64-symbol alphabet (126 bits). You can write the same thing with randomBytes, because 64 divides 256 evenly, which means byte & 63 is unbiased without rejection. (With an alphabet whose size does not divide 256, use randomInt or rejection sampling, as above.)

Node.js A nanoid-style generator

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.

How long should an ID be? That depends on how many you will create and how bad a collision is. With a random n-bit ID you expect the first collision after about 2^(n/2) IDs. For 122 bits that is around 2^61, which is more than any system will ever generate. For 48 bits it is about 16 million IDs, which is small. Public, guessable-damage IDs (invite links) need to be long; internal display labels can be short.

Repeatable randomness for demos and tests

Sometimes you want randomness that looks random but is identical on every run: a simulation you want to reproduce, a test using generated data, a documentation example. Math.random cannot be seeded in JavaScript, but a small PRNG can. The classic compact choice is mulberry32: fast, 32 bits of state, and good enough for non-security work.

Node.js A seeded generator gives the same sequence every time

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.

Because the algorithm is plain integer arithmetic, the output is the same on every machine, and the numbers above are exactly what you get. A seeded generator is how you write a test such as "shuffle 1,000 items with seed 7 and check the result" without flaky failures. In tests of code that uses secure randomness (tokens, UUIDs), do not try to fix the values. Test the properties instead: length, character set, uniqueness, and that two calls differ. Or inject the random source as a parameter, as the shuffle above does.

The Fisher-Yates loop deserves a remark: array.sort(() => Math.random() - 0.5), a popular one-liner, is a biased shuffle, because the comparison is inconsistent and the result depends on the sorting algorithm. Use Fisher-Yates.

Choosing the right tool

Need Use
Session token, API key, reset link randomBytes(32).toString('base64url')
Unique record ID, no ordering randomUUID()
Sortable ID for database rows ULID or UUID v7 (hand-written or a library)
Short public ID nanoid-style with randomBytes or randomInt
Number in a range, secure randomInt(min, max)
Shuffle or sample for display Math.random() with Fisher-Yates
Reproducible simulation or test data A seeded PRNG such as mulberry32
Password-like secret to show a person randomInt over a large alphabet, 16+ characters

Common mistakes

  • Using Math.random for tokens. The single most common error. Search your code for it near words like "token", "session", "reset".
  • Building tokens from Date.now() or counters. Predictable.
  • Reusing a seed in production. A seeded PRNG is repeatable by design, which is the opposite of secret.
  • Truncating too hard. A 4-character ID has a collision chance very quickly. Do the birthday-bound arithmetic.
  • Assuming a UUID is a permission. Always authorize access separately from knowing an ID.
  • Printing secrets to logs. Tokens belong nowhere near console.log (see Configuration, Secrets and Environment).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is Math.random() unsuitable for generating session tokens?

    Math.random is a fast PRNG whose internal state can be recovered from its outputs. Tokens need a CSPRNG such as crypto.randomBytes.
  2. 2. What does crypto.randomInt(1, 7) return?

    The upper bound of randomInt is exclusive, so (1, 7) gives 1 to 6, like a die.
  3. 3. What is modulo bias?

    256 values mapped with % 6 give some faces 43 chances and others 42. Rejection sampling, as used by randomInt, avoids it.
  4. 4. What is the advantage of a ULID over a random UUID v4 as a database key?

    The time prefix makes IDs roughly ordered, which is friendlier to indexes. It does not make them secret, and Node.js has no built-in generator.
  5. 5. How do you get a repeatable sequence of pseudo-random numbers for a test?

    Math.random cannot be seeded, and crypto functions are intentionally unpredictable. A seeded PRNG gives the same sequence for the same seed.

Summary

  • Math.random() is fine for variety (shuffling for display, jitter) and wrong for anything an attacker could guess.
  • node:crypto gives secure randomness: randomBytes, randomInt (upper bound exclusive, no bias), randomUUID, getRandomValues.
  • Use 32 random bytes encoded as hex or base64url for tokens. Short human codes need expiry and attempt limits.
  • Avoid modulo bias: use randomInt, rejection sampling, or an alphabet whose size divides 256.
  • UUID v4 is a good unique ID, not a secret and not ideal as a clustered primary key. ULID/UUID v7 put time first so IDs sort.
  • Compute collision risk with the birthday bound (about 2^(n/2) IDs for n bits).
  • A seeded PRNG such as mulberry32 gives repeatable "random" data for tests and demos but is never secure.
  • Test random code by its properties (length, characters, uniqueness), not its values.

Next: Encryption: AES, RSA and Keys