Generate UUIDs in JavaScript with crypto.randomUUID()

By

Published · Updated

Tagged: Web Platform

Generate a v4 UUID in JavaScript with crypto.randomUUID(), no library needed. Plus a fallback for HTTP pages, how to validate and compare UUIDs, and Node.js details.

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 is a version 4 UUID as defined in RFC 9562, which replaced the older 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.

A fallback for plain HTTP pages

Sometimes you can’t add HTTPS, like a tool on an internal network. crypto.getRandomValues() is the one Crypto method that also works in insecure contexts, so you can build a v4 UUID from it:

function uuidv4() {
  if (typeof crypto.randomUUID === 'function') {
    return crypto.randomUUID()
  }

  const bytes = crypto.getRandomValues(new Uint8Array(16))
  bytes[6] = (bytes[6] & 0x0f) | 0x40 // version 4
  bytes[8] = (bytes[8] & 0x3f) | 0x80 // variant 10xx

  const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('')
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}

The two lines in the middle set the bits that make it a valid v4 UUID: the version nibble becomes 4, and the first character of the fourth group becomes 8, 9, a or b. The rest of the 128 bits stay random.

Don’t reach for a Math.random() version you find online. It’s not cryptographically strong, so the values are easier to predict.

How do I check if a string is a valid UUID?

Use a regular expression that checks the shape, the version and the variant:

const UUID_V4 =
  /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

UUID_V4.test('5b6def99-2aa2-4a48-a30c-7b9c11cc9190') // true
UUID_V4.test('not-a-uuid') // false

The i flag matters. The UUID spec allows uppercase, lowercase or mixed case, and some systems (like .NET or a database tool) give you uppercase. crypto.randomUUID() always returns lowercase.

That also means you shouldn’t compare UUIDs with a plain === when they come from different sources:

const a = '5B6DEF99-2AA2-4A48-A30C-7B9C11CC9190'
const b = '5b6def99-2aa2-4a48-a30c-7b9c11cc9190'

a === b // false
a.toLowerCase() === b.toLowerCase() // true

Normalize to lowercase before you store or compare them.

Can I sort them by creation time?

No. A v4 UUID is pure randomness, so there’s no order in it. Sort by a separate createdAt field.

If you want IDs that sort by time, look at UUID v7, which puts a millisecond timestamp in the first 48 bits. I explain the difference in UUID v4 vs v7. Node.js 26.1 added crypto.randomUUIDv7() in the node:crypto module.

Node.js details

randomUUID() landed in node:crypto in Node.js 14.17 and 15.6. The global crypto object came later: since Node.js 19 it’s there without a flag. On older versions, a script that calls crypto.randomUUID() without the import fails with ReferenceError: crypto is not defined, so import it from node:crypto.

By default Node.js generates enough random data for 128 UUIDs at once and caches it, which makes generating many of them faster. You can skip the cache:

import { randomUUID } from 'node:crypto'

randomUUID({ disableEntropyCache: true })

You rarely need this. The output is just as random either way.

TypeScript

You don’t need a type package. In TypeScript’s DOM types, crypto.randomUUID() returns a template literal type:

const id: `${string}-${string}-${string}-${string}-${string}` =
  crypto.randomUUID()

You can assign it to a plain string too. The template type only helps when you want a function to accept UUID-shaped strings and reject others at compile time.

Want me to talk about your product? You can sponsor this site.

Related posts about platform: