How to Generate a UUID in JavaScript Without a Library
For years, generating a UUID in JavaScript meant installing a package like uuid or nanoid, because there was no built-in way to do it. That's no longer true — modern browsers and recent versions of Node.js (14.17+) both expose crypto.randomUUID(), a native function that generates a proper, cryptographically random version 4 UUID with zero dependencies.
Using it is as simple as calling crypto.randomUUID() — no import, no setup. It returns a standard 36-character UUID string like 'a1b2c3d4-e5f6-47a8-9b2c-123456789abc', formatted exactly the way you'd expect, hyphens included.
The important detail is that crypto.randomUUID() is only available in secure contexts — meaning pages served over HTTPS, or localhost during development. If you're serving your site over plain HTTP in production (which you shouldn't be doing anyway) or accessing it via a raw IP address instead of localhost, the function won't be available on window.crypto, and you'll need a polyfill or library as a fallback.
If you need to support older browsers or non-secure contexts, the fallback approach uses crypto.getRandomValues() (which has much broader support) combined with some bit manipulation to format the random bytes into the correct UUID v4 structure — this is exactly what libraries like uuid do under the hood, just wrapped in a convenient function.
It's worth being clear about what "random" means here for security purposes. crypto.randomUUID() and crypto.getRandomValues() both use the operating system's cryptographically secure random number generator, unlike Math.random(), which is not cryptographically secure and should never be used to generate identifiers that need to be unguessable, like session tokens or password reset codes.
One more thing worth knowing: UUID v4 (the type crypto.randomUUID() generates) is fully random, which is great for unpredictability but not ideal for database primary keys at scale, since random values fragment B-tree indexes. If you're generating IDs for database rows rather than one-off tokens, look into UUID v7, which embeds a timestamp so IDs generated close together sort close together — though as of now, v7 generation still isn't built into JavaScript natively.
If you just need to quickly generate one or a batch of UUIDs while testing something — without writing any code at all — our UUID Generator produces cryptographically random v4 UUIDs in bulk, with options for hyphens and case, right in the browser.
Found this helpful?
SyncTonight's tools and guides are free and always will be. If this post saved you some debugging time, a coffee goes a long way — no pressure, just appreciated.
☕ Buy me a coffee