To generate a UUID in JavaScript in 2026, use the built-in crypto.randomUUID(). No library, no npm install, one line:
const id = crypto.randomUUID();
// "36b8f84d-df4e-4d49-b662-bb00a661f0ad"That returns a fresh RFC 4122 version 4 (random) UUID as a 36-character string every time you call it. It is part of the Web Crypto API, ships in every current browser and in Node, and uses a cryptographically secure random source, so you do not need uuid, nanoid, or a hand-rolled Math.random() generator for the common case. Below I cover the secure-context gotcha, the Node forms, the rest of Web Crypto in Node (getRandomValues, crypto.subtle, shims for Jest), and when v4 is the wrong version.
The David Walsh post that a lot of people still land on warned that "browser support is very patchy." That was true years ago. It is no longer true, and that single stale sentence is why people still reach for a library out of habit. crypto.randomUUID() is now Baseline: Chrome and Edge 92, Firefox 95, Safari 15.4, and it has been there since Node 14.17. The one real catch is not support, it is the secure-context rule below.
The #1 gotcha: it needs a secure context
Here is the trap that sends people back to a library after crypto.randomUUID returns undefined or throws on their dev box: the whole crypto object is only populated in a secure context. That means HTTPS, or http://localhost (and 127.0.0.1, and file://), but not a plain http:// origin. Open your app at http://192.168.1.50:3000 or http://staging.internal over plain HTTP and crypto.randomUUID is not a function.
// On https:// or http://localhost → works
crypto.randomUUID(); // "36b8f84d-..."
// On a plain http:// origin (LAN IP, internal hostname):
typeof crypto; // "object", but...
crypto.randomUUID; // undefined → "crypto.randomUUID is not a function"localhost is treated as secure by the spec, which is why it works in dev and then breaks the moment a colleague hits your machine by IP. The fix is not a polyfill, it is to serve the page over HTTPS (a self-signed cert for the LAN, or a tunnel). If you genuinely cannot, see the fallback at the end. This secure-context requirement is also the answer to nearly every "why is crypto.randomUUID undefined" question on the web, and it trips people up the exact same way with the Clipboard API, which only exposes navigator.clipboard on a secure origin.
In Node.js
Node exposes the same API, with a version wrinkle worth knowing. Since Node 19, crypto is a global the same way it is in the browser (the Web Crypto in Node.js section below covers the rest of that surface), so the browser line works unchanged:
// Node 19+: crypto is global, no import
const id = crypto.randomUUID();On any Node from 14.17 onward (which is to say, anything you should still be running), import it explicitly. This is the form I default to in a module because it does not depend on the Node version having the global:
import { randomUUID } from "node:crypto";
const id = randomUUID();CommonJS is the same idea with require:
const { randomUUID } = require("node:crypto");
const id = randomUUID();There is no secure-context concept in Node, so the HTTPS rule above is purely a browser thing. If you see crypto.randomUUID is not a function in Node, you are on a version older than 14.17 and the answer is to upgrade Node, not to add a dependency. As a bonus, the native call benchmarks faster than the userland uuid package's v4(), because it drops straight into the runtime's CSPRNG.
Web Crypto in Node.js
randomUUID() is one method on a bigger object. As of Node 19 the whole Web Crypto API is exposed as globalThis.crypto, with no import, no shim, and no flag, so browser crypto code runs unchanged:
// Works in Node 19+ and in any browser, no import:
const id = globalThis.crypto.randomUUID();
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);globalThis.crypto is the standard name; bare crypto resolves to the same global in a module, the same way it does in a browser. That is the point of Web Crypto living on globalThis: one piece of crypto code that runs in Node, the browser, Deno, and the edge runtimes without branching.
This was not always the case, which is why so many old snippets still carry a shim. The history has three separate steps:
- Node 15.0 (October 2020): Web Crypto arrived as an experimental module export, reachable only through
require('node:crypto').webcrypto. There was no global. - Node 17.6 and 16.15 (2022): a global
cryptowas added, but only behind the--experimental-global-webcryptoflag. - Node 19.0 (October 2022): the flag was no longer needed, so the global is there by default, and the Web Crypto API itself stopped being experimental (apart from a few newer algorithms). The Node docs kept the global
cryptoentry marked experimental until Node 23.0.
If you are on a supported LTS (Node 22, 24, or 26), you are well past the point where any of this matters.
globalThis.crypto vs the node:crypto module
Node ships two crypto surfaces, and confusing them is the usual source of "why doesn't this method exist" errors.
node:crypto (the Node module) | globalThis.crypto (Web Crypto) | |
|---|---|---|
| How you get it | import { createHash } from "node:crypto" | global, no import |
| Style | Node-specific, mostly synchronous | W3C standard, promise-based |
| Hashing | createHash("sha256").update(x).digest() | await crypto.subtle.digest("SHA-256", x) |
| Random bytes | randomBytes(16) (Buffer) | crypto.getRandomValues(new Uint8Array(16)) |
| Portability | Node only | Node, browsers, Deno, edge |
They overlap but are not interchangeable. node:crypto is the older, broader, Node-native API (HMAC, ciphers, key pair generation, the lot), and most of it is synchronous and returns Buffers. Web Crypto's crypto.subtle is the standardized async interface that returns Promises and ArrayBuffers, and it is the one to use when the same code has to run in a browser too. crypto.webcrypto from the module is the same object as the global, so require('node:crypto').webcrypto === globalThis.crypto holds; reach for the explicit form only when you want to be unambiguous, or when a tool still strips globals.
Random bytes and hashes
Next to randomUUID(), the two calls I actually use are random bytes and a digest. crypto.getRandomValues() fills a typed array with cryptographically strong random values in place (and returns the same array):
function te_token(len = 32) {
const buf = crypto.getRandomValues(new Uint8Array(len));
return Buffer.from(buf).toString("hex");
}getRandomValues mutates the array you pass and caps at 65,536 bytes per call. If you only need bytes and are Node-only, node:crypto's randomBytes(len) is shorter and has no size cap.
crypto.subtle.digest() is async and works on bytes, not strings, so encode first:
async function te_sha256(text) {
const data = new TextEncoder().encode(text);
const hash = await crypto.subtle.digest("SHA-256", data);
return [...new Uint8Array(hash)]
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}The Node-native one-liner for the same result is createHash("sha256").update(text).digest("hex"). Use the subtle version when portability matters; use the module version when you are staying in Node and want it synchronous. Because subtle returns promises, the await patterns in my JavaScript Promises guide apply directly.
When you still need a crypto shim
The global is there in modern Node, so the only reason to shim is an environment that hides it:
- Old runtimes. Anything before Node 15 has no Web Crypto at all; Node 15 to 18 has it through
require('node:crypto').webcrypto, and only from 16.15/17.6 as a global, behind the flag. If you must support those, set the global yourself:globalThis.crypto ??= require("node:crypto").webcryptoin CommonJS, orimport { webcrypto } from "node:crypto"; globalThis.crypto ??= webcryptoin an ES module. - jsdom test environments. This is the common modern case. Jest's
jsdomtest environment provides awindowbut historically did not wire upcrypto.subtle, so a component that callscrypto.randomUUID()blows up under test even though it works in the real browser and in plain Node.
The fix for jsdom is a one-liner in your test setup file:
// jest.setup.js, give jsdom the real Web Crypto
import { webcrypto } from "node:crypto";
// jsdom usually provides a partial crypto object, so test for the methods, not the object
if (typeof globalThis.crypto?.randomUUID !== "function" || !globalThis.crypto?.subtle) {
Object.defineProperty(globalThis, "crypto", { value: webcrypto, configurable: true });
}The check is on the methods because the failure under jsdom is a crypto object that exists but lacks randomUUID() (jsdom only added it in 22.1) or subtle; a plain if (!globalThis.crypto) test would skip the shim exactly when you need it. Object.defineProperty is used because crypto can be a getter-only property there, where a plain assignment silently does nothing. That is the whole shim. Avoid the crypto-browserify / crypto-js polyfills for this: they predate native Web Crypto and you do not need them on any supported Node. And remember the browser half of the story: the secure-context rule above still applies there, so code that is happy in Node can still find crypto.subtle missing on a plain-HTTP page.
It generates a v4 UUID, and sometimes that's the wrong one
crypto.randomUUID() always returns a v4 UUID: 122 random bits, no embedded timestamp, no machine info. Collisions are not "impossible," but the probability is small enough to ignore for any realistic application, so treating it as unique is fine.
What v4 is bad at is ordering. Because it is fully random, consecutive v4 UUIDs land all over the place. Use one as a primary key and every insert scatters across the B-tree index, which fragments the index and hurts write throughput on a busy table. The fix is v7, a newer UUID format whose leading bits are a millisecond timestamp, so freshly minted IDs sort roughly in creation order and insert sequentially. The platform does not generate v7 yet (crypto.randomUUID() is v4 only, and Node has no native v7 as of mid-2026), so for time-ordered IDs you do still need a library, for example the uuid package's v7() or uuidv7.
If the reason you want a UUID is a database key, the version choice matters more than the generation syntax. I cover the storage and indexing trade-offs in depth in how to store a UUID in MySQL (the BINARY(16) vs CHAR(36) decision, and where v7 earns its keep) and storing a UUID in PostgreSQL with the native uuid type.
Fallback for ancient or insecure-context environments
You should almost never need this. If you are stuck on a plain-HTTP origin you cannot upgrade, or supporting a runtime old enough to lack randomUUID, build a v4 UUID from crypto.getRandomValues, which has slightly wider reach and is still cryptographically secure:
function teRandomUuid() {
const bytes = crypto.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0"));
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
}This works on a plain-HTTP page too: getRandomValues() is the one Crypto method browsers expose outside a secure context, so it fills the gap where randomUUID() is missing, whether from an insecure origin or an older runtime. Never substitute Math.random() here: it is not cryptographically secure and is the wrong tool for an identifier.
FAQ
Almost always because the page is not in a secure context. The whole Web Crypto API is only available over HTTPS or on http://localhost, never on a plain http:// origin like a LAN IP or an internal hostname. Serve the page over HTTPS and it works. In Node, the same error means you are on a version older than 14.17; upgrade Node.
Version 4: 122 bits of cryptographically secure randomness, with no timestamp or machine identifier. If you need a time-ordered, database-friendly identifier, you want version 7 instead, which the platform does not generate natively yet, so v7 requires a library.
Not for a random v4 UUID. crypto.randomUUID() covers that natively in every current browser and in Node, and it benchmarks faster than the package. Reach for the uuid library (or uuidv7) only when you specifically need v7, v5/v3 namespaced UUIDs, or parsing and validation helpers.
No, not on Node 19 or later. globalThis.crypto (and the bare crypto global in a module) is available with no import. You only import from node:crypto when you want the Node-native API (randomBytes, createHash, createHmac, key generation) rather than the standard Web Crypto interface.
Node 19 (October 2022) removed the need for the --experimental-global-webcrypto flag, so globalThis.crypto is exposed by default from then on, and the Web Crypto API itself stopped being experimental in the same release. Before that, Web Crypto arrived in Node 15 (October 2020) as require('node:crypto').webcrypto only, and the global was added in Node 17.6 and 16.15 behind that flag. The Node docs marked the global crypto entry fully non-experimental in Node 23.
Not guaranteed, but the collision probability for v4 is negligible for any realistic workload, so you can safely treat the output as unique. It is generated with a cryptographically secure random number generator, not Math.random().
See also
- How to store a UUID in MySQL: the
BINARY(16)vsCHAR(36)decision and the v4-vs-v7 index-fragmentation problem. - Storing a UUID in PostgreSQL: using the native
uuidtype instead of a text column. - Modern JavaScript array methods: the 2026-current toolkit (
at,flat,toReversed,Object.groupBy) and the mutation trap. - Read environment variables in Node.js without dotenv: keep secrets and keys out of the source tree, the natural companion to doing crypto in Node.
- JavaScript object methods:
keys,values,entries,fromEntries,freeze, and null-prototype maps.
Sources
Authoritative references this article was fact-checked against.
- Crypto: getRandomValues() method (MDN)developer.mozilla.org
- jsdom issue 3784: Add crypto.randomUUID()github.com
- Crypto: randomUUID() method (MDN)developer.mozilla.org
- Secure contexts (MDN)developer.mozilla.org
- Node.js crypto.randomUUID (official docs)nodejs.org
- Node.js global crypto (official docs)nodejs.org
- Web Crypto API, Node.js documentation (official)nodejs.org
- Crypto, Node.js documentation (official)nodejs.org
- Web Crypto API, MDNdeveloper.mozilla.org





