Developer Documentation
TypeScript
Updated September 18, 2026

Generate a UUID in TypeScript

Generate, validate, and parse RFC 4122/9562 UUIDs in TypeScript with nominal branded types and runtime guards.

TypeScript brings compile-time type safety to UUIDs. By pairing runtime Web Crypto generation with nominal branded types and type guards, you can prevent accidental parameter swapping (such as passing a UserId where an OrderId is expected) while maintaining zero-overhead JavaScript compilation.

Quick Start#

The native Web Crypto API returns a typed string directly:

TypeScript
1// Zero-dependency modern TypeScript2const id: string = crypto.randomUUID();34console.log(id);5// Output: "f47ac10b-58cc-4372-a567-0e02b2c3d479"

Creating Type-Safe Branded UUIDs#

In large codebases, treating all identifiers as generic string types frequently leads to subtle bugs where two different entities' IDs are swapped in function arguments:

TypeScript
1// Define nominal branded types2export type UUID = string & { readonly __brand: unique symbol };3export type UserId = UUID & { readonly __userBrand: unique symbol };4export type OrderId = UUID & { readonly __orderBrand: unique symbol };56// Safe constructor / cast helper7export function asUUID(value: string): UUID {8  if (!isValidUUID(value)) {9    throw new TypeError(`Invalid UUID format: "${value}"`);10  }11  return value as UUID;12}1314// Example service signature preventing parameter inversion15function processOrder(userId: UserId, orderId: OrderId): void {16  console.log(`Processing order ${orderId} for user ${userId}`);17}

Runtime Validation & Type Guards#

Use a custom type guard to refine untyped inputs (such as API route parameters or form submissions) into strongly typed UUID instances:

TypeScript
1const UUID_REGEX =2  /^[--f]{}-[--f]{}-[-][--f]{}-[][--f]{}-[--f]{}$/i;34export function isValidUUID(val: unknown): val is UUID {5  return typeof val === "string" && UUID_REGEX.test(val);6}78// Usage in an API controller or handler9function handleRequest(rawId: string) {10  if (isValidUUID(rawId)) {11    // rawId is now safely typed as UUID12    loadEntityById(rawId);13  } else {14    throw new Error("Invalid UUID parameter");15  }16}

Using the uuid Package with TypeScript#

When using the uuid package, TypeScript types are bundled natively without requiring a separate @types package:

Bash
1npm install uuid
TypeScript
1import { v4 as uuidv4, v7 as uuidv7, validate as validateUuid } from "uuid";23// Generate UUIDv44const sessionToken: string = uuidv4();56// Generate time-ordered UUIDv77const recordId: string = uuidv7();89// Check version10const isOk: boolean = validateUuid(recordId);

Parsing to Uint8Array for Database Adapters#

For low-level database operations (such as PostgreSQL binary UUID columns or MongoDB binary subtypes), convert string UUIDs to typed byte buffers:

TypeScript
1import { parse as parseUuid, stringify as stringifyUuid } from "uuid";23function uuidToBuffer(id: string): Uint8Array {4  return parseUuid(id);5}67function bufferToUuid(buf: Uint8Array): string {8  return stringifyUuid(buf);9}

Best Practices#

  1. Use Branded Types: Prevent accidental ID cross-assignment in domain models and services.
  2. Apply Type Guards at System Boundaries: Always validate incoming strings from HTTP requests or message queues before casting to branded UUID types.
  3. Adopt UUIDv7 for Database Keys: When using SQL databases with B-Tree indexes, UUIDv7 provides linear page-insertion performance without sacrificing distributed generation.

References#

Implement UUID in other languages: