How to generate a UUID
Short answer
crypto.randomUUID() returns a random UUID of version 4: 36 characters with hyphens:
const id = crypto.randomUUID();
console.log(id.length, id.split('-').length);Output:
36 5Checking the format
A UUID consists of hex digits in groups of 8, 4, 4, 4 and 12:
const isUuid = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
console.log(isUuid(crypto.randomUUID()));
console.log(isUuid('123-abc'));Output:
true
falseIn Node.js
In Node.js the same function can also be imported from node:crypto:
import { randomUUID } from 'node:crypto';
console.log(randomUUID().length);Output:
36Common mistake
In the browser crypto.randomUUID() works only on secure pages: https or localhost. On a plain http page it is missing. Do not build ids from Math.random(), its values are predictable and can repeat.
console.log(typeof crypto.randomUUID);Output:
functionFunctions used in this recipe
- crypto.randomUUID — Creates a random unique identifier (UUID).