Generate UUIDs in JavaScript with crypto.randomUUID()

By

Learn how to generate a v4 UUID in JavaScript with window.crypto.randomUUID(), a built-in Web Crypto API method that needs no external libraries.

~~~

To generate a UUID in JavaScript, call crypto.randomUUID(). It’s built into all modern browsers and into Node.js, so you don’t need to install anything:

const uuid = crypto.randomUUID()
console.log(uuid) // '5b6def99-2aa2-4a48-a30c-7b9c11cc9190'

You get back a v4 UUID (Universally Unique Identifier) as a 36-character string. Four hyphens split it into five groups, and the first character of the third group is always 4, which marks the version.

A v4 UUID is generated from random data. The chance of two of them colliding is so small you can treat every one as unique, without coordinating with a server or a database.

When would you use it?

Any time you need an identifier on the client before the server assigns one.

Say you’re building a todo app and you create items locally first, then sync them later:

const todo = {
  id: crypto.randomUUID(),
  text: 'Buy milk',
  done: false
}

The item has a stable id from the moment it exists. You can use it as a React key, store it in localStorage, and send it to the backend when the sync happens.

Why use it instead of a library?

Before this method landed, we all installed packages like uuid to do the same job. Now the platform gives us three things for free:

  1. No dependencies: nothing to install, nothing to bundle.
  2. Security: the randomness comes from a cryptographically strong generator, not Math.random().
  3. Standards-compliant: the output follows RFC 4122.

It works in Node.js too. The crypto global is available in recent versions, or you can import it explicitly:

import { randomUUID } from 'node:crypto'

console.log(randomUUID()) // '36b8f84d-df4e-4d49-b662-bcde71a8764f'

Watch out for the secure context requirement

In browsers, crypto.randomUUID() is only available in a secure context. That means pages served over HTTPS, plus localhost during development.

If you load your page over plain http:// from another machine on your network, the method is not there and you get:

TypeError: crypto.randomUUID is not a function

The crypto object exists, but randomUUID is missing from it. The fix is to serve the page over HTTPS, or test on localhost where the restriction doesn’t apply.

If you need a few UUIDs right now (or want to compare them with nanoid and ULID), I built a free ID generator tool for that.

~~~

Related posts about platform: