How to Generate a UUID in JavaScript
By SimpleTools24Published 3 min read
The simplest way to generate a UUID in JavaScript is crypto.randomUUID(), which returns a random version 4 UUID string such as "36b8f84d-df4e-4d49-b662-bcde71a8764f". It's built into modern browsers (on HTTPS pages and localhost) and into Node.js, with no library needed. For other versions, such as time-ordered version 7, use the widely used uuid package from npm. Avoid copy-pasted snippets based on Math.random(), which aren't designed for unique IDs.
In this guide
In the Browser
const id = crypto.randomUUID();
console.log(id); // "36b8f84d-df4e-4d49-b662-bcde71a8764f"crypto.randomUUID() uses the browser's cryptographically secure random number generator and sets the version and variant bits correctly. Two requirements:
- Secure context. The method is only available on pages served over HTTPS, or on
localhostduring development. On a plainhttp://page,crypto.randomUUIDis undefined. - Modern browser. All current major browsers support it.
If you must support an insecure context, crypto.getRandomValues() is available more widely and can build a v4 UUID, or you can use the uuid package.
In Node.js
import { randomUUID } from 'node:crypto';
const id = randomUUID();Recent Node.js versions also expose the Web Crypto API globally, so crypto.randomUUID() works without an import. Either form returns a version 4 UUID.
With the uuid Package
npm install uuidimport { v4 as uuidv4, v7 as uuidv7, validate, version } from 'uuid';
uuidv4(); // random UUID
uuidv7(); // time-ordered UUID
validate('not-a-uuid'); // false
version(uuidv7()); // 7The package also supports name-based v3 and v5 UUIDs, plus v1 and v6, and includes validate, version, parse and stringify helpers. It's a good choice when you need a version other than v4, or consistent behaviour across very old environments. For time-ordered IDs, how to generate UUID v7 compares options in several languages.
In TypeScript
crypto.randomUUID() is typed to return a template literal type of the form ${string}-${string}-${string}-${string}-${string} in TypeScript's DOM typings, which you can treat as a string. With the uuid package, types are included.
type UserId = string;
const userId: UserId = crypto.randomUUID();Why Not Math.random()?
You'll find snippets like this online:
// Don't use for real IDs
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { /* Math.random() ... */ });They produce strings in the right format, but Math.random() isn't a cryptographically secure source and its quality varies between engines. That raises the chance of duplicates, especially across many clients, and makes values more predictable. With crypto.randomUUID() available everywhere that matters, there's no reason to use these.
Common Tasks
| Task | Code |
|---|---|
| Uppercase | crypto.randomUUID().toUpperCase() |
| Without hyphens | crypto.randomUUID().replaceAll('-', '') |
| Several at once | Array.from({ length: 10 }, () => crypto.randomUUID()) |
| Validate | uuid.validate(s) or a regex |
| Get version | uuid.version(s) |
For validation without a library, see how to validate a UUID in JavaScript and Python, which includes a strict regex.
Don't Use UUIDs as Secrets
A UUID from crypto.randomUUID() is hard to guess, but UUIDs aren't designed as security tokens, and they're often logged and exposed in URLs. For session tokens, password reset links or API keys, generate dedicated random tokens, for example 32 bytes from crypto.getRandomValues() encoded in base64url.
Generating UUIDs Without Code
When you just need IDs for a fixture file, a database seed or a config, the UUID v4 generator creates up to 1,000 at once in your browser using the same Web Crypto API, with options for uppercase, compact or braced formats and quotes for pasting into code. For time-ordered IDs, the UUID v7 generator works the same way.
UUIDs in Front-End Frameworks
- React keys: generate IDs when items are created, not during render. Calling
crypto.randomUUID()inside a component's render gives every element a new key on each render, which defeats React's reconciliation. For accessibility IDs that link labels and inputs, React'suseId()hook is the right tool instead. - Optimistic UI: generating the ID on the client lets you show a new item immediately and reconcile with the server response later, using the same ID.
- Server-side rendering: make sure IDs generated on the server are passed to the client rather than regenerated, or hydration may produce mismatches.
Storing and Sending UUIDs
- Send UUIDs as strings in JSON; there's no native UUID type.
- Normalise to lowercase before comparing or storing.
- In databases with a native UUID type, let the driver convert the string.
Frequently Asked Questions
Is crypto.randomUUID() safe to use?
Yes, for unique identifiers. It uses a cryptographically secure random source and produces standard version 4 UUIDs.
Why is crypto.randomUUID undefined?
Your page isn't a secure context (HTTPS or localhost), or the environment is very old.
Does crypto.randomUUID() create UUID v7?
No. It only generates version 4. Use the uuid package's v7() for time-ordered IDs.
Do I still need the uuid npm package?
Only for versions other than 4, extra helpers, or unusual environments. For random UUIDs, the built-in method is enough.
Summary
Use crypto.randomUUID() for random UUIDs in browsers and Node.js, the uuid package for v7 and other versions, and never Math.random() snippets. Keep UUIDs for identifiers, not secrets.
Related tools
Sources
- Crypto: randomUUID() method – MDN Web Docs (opens in a new tab)
- uuid (npm package) – uuidjs (opens in a new tab)
- crypto.randomUUID([options]) – Node.js documentation (opens in a new tab)
Related articles
- Generate a UUID in Pythonuuid4(), uuid7() on Python 3.14+, uuid5() for deterministic IDs, and converting UUIDs between strings, bytes and ints.
- Validate a UUID in CodePractical validation in JavaScript and Python, plus notes for Java and C#, and how strict your checks should be.
- Generate UUID v7Working UUID v7 examples for popular languages and databases, and what to look for in a v7 library.