Skip to content
Tutorials Center
My learning

Topics

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

Node.js crypto.randomUUID() method

Reference for crypto.randomUUID() in Node.js: generate a random version 4 UUID string, the format it returns, the options, and when UUIDs are the wrong choice.

crypto.randomUUID() returns a new random UUID as a 36-character lowercase string such as 3b241101-e2bb-4255-8caf-4136c566a962. It generates version 4 UUIDs: 122 bits of randomness from the secure generator, plus fixed bits that mark the version and variant.

It exists both as a global (crypto.randomUUID()) and as randomUUID() exported from node:crypto. Both produce the same kind of value; the Node export additionally accepts an options object.

NODE
const id = crypto.randomUUID();

Try it

Node.js Generating and checking a UUID

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 The Node.js module version

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.randomUUID()                       // global, no arguments
require('node:crypto').randomUUID([options])
Name Description
options.disableEntropyCache Node.js only. By default Node generates random data for UUIDs in batches and caches it for speed. Set true to skip the cache. Rarely needed.

Returns: a string in the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where y is 8, 9, a or b.

Errors: the global version takes no arguments. The module version throws a TypeError if options is not an object.

Usage notes

  • Random, not sequential. Version 4 UUIDs have no time order, so they are poor database primary keys on large B-tree indexes: inserts land at random places. Time-ordered formats (UUID version 7, ULID) are friendlier there; Node.js has no built-in generator for them.
  • Collisions are astronomically unlikely with 122 random bits, but the guarantee relies on a good random source, which Node provides.
  • Not a secret. A UUID is an identifier. For session tokens and password reset links prefer a dedicated token of at least 128 bits from crypto.randomBytes(), and treat it like a password.
  • Always lowercase with hyphens. Normalize input from other systems before comparing.
  • Fast. Because of the entropy cache, generating thousands per second costs very little.
  • Validation is a regular expression like the one above; there is no built-in isUUID().
  • Browsers need a secure context (HTTPS or localhost) for crypto.randomUUID().