Code guide

Generate UUIDs in TypeScript

Generate UUIDs in TypeScript with crypto.randomUUID in browsers and Node, plus typed validation helpers.

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);
}

FAQ

Generate UUIDs in TypeScript questions

Does crypto.randomUUID work in TypeScript?

Yes. It is a runtime API available in modern browsers and Node, and TypeScript types it as returning a string.

How do I type a UUID in TypeScript?

A UUID is a string. Use a type guard like isUuid to narrow unknown input, or a branded type for stricter APIs.

Do I need a library?

Only for UUID v7 or to support older runtimes without crypto.randomUUID.

Generate UUID in TypeScript - crypto.randomUUID