TypeScript uses the same runtime APIs as JavaScript, so crypto.randomUUID is the simplest UUID v4 generator in modern browsers and Node. Types add a little extra safety at the boundary.
Key takeaways
- crypto.randomUUID() returns a typed string with no dependency.
- In Node, import randomUUID from node:crypto.
- Use a library only for UUID v7 or older runtime support.
Generate a UUID
In a secure browser context or Node 19+, crypto.randomUUID works directly. In Node you can also import it explicitly.
// Browser or Node 19+
const id: string = crypto.randomUUID();
// Node, explicit import
import { randomUUID } from "node:crypto";
const nodeId = randomUUID();A typed validation helper
Narrow unknown input to a UUID string at the boundary with a small type guard so the rest of your code can trust it.
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isUuid(value: unknown): value is string {
return typeof value === "string" && UUID_RE.test(value);
}