crypto.randomUUID() is part of the Web Crypto API. It returns a random version 4 UUID string generated from a cryptographically secure source, and it is available both in browsers and in Node.js (16.7+).
It is the simplest, dependency-free way to create UUIDs in JavaScript runtimes, with one caveat: in browsers it only works in a secure context.
In the browser
On the global crypto object, call randomUUID(). The page must be served over https (or localhost during development) for crypto to be available.
// Browser (secure context: https or localhost)
const id = crypto.randomUUID();
console.log(id);In Node.js
In Node.js, import randomUUID from the built-in crypto module (or use the global crypto in newer versions). No package installation is required.
import { randomUUID } from "node:crypto";
console.log(randomUUID()); // "a1b2c3d4-e5f6-4789-8abc-1234567890ef"Why use crypto.randomUUID()?
Because it draws on the platform CSPRNG, its output is suitable for identifiers that should be unpredictable. It also avoids pulling in a dependency just to create an ID.
If crypto is undefined in the browser, you are almost certainly on an insecure (http) origin — serve the page over https and it will work.
Frequently asked questions
- Why is crypto.randomUUID() undefined?
- In browsers the Web Crypto API is only exposed in secure contexts. If you are on an http page, switch to https or localhost and it will be defined.
- Does crypto.randomUUID() work in Node.js?
- Yes, from Node.js 16.7 onward. Import randomUUID from the built-in node:crypto module.
- What UUID version does crypto.randomUUID() return?
- It returns a version 4 (random) UUID.
