Skip to main content
TS

How to Generate UUID in TypeScript

Using crypto.randomUUID()

TypeScript doesn't need a special UUID library to hand you a valid identifier — crypto.randomUUID() works exactly as it does in JavaScript, and you can layer type safety on top with a few lines of your own code. Call it directly for a random, RFC 4122-compliant UUID as a string, or wrap the result in a branded type so the compiler catches any accidental mixing of UUIDs with ordinary strings. Below you'll find copy-paste ready code for generating a TypeScript UUID, building a type-safe wrapper around one, and the uuid npm package's typed alternatives for v1, v5, and v7. Use the java uuid guide to implement UUID-based entity IDs in Hibernate with optimal database compatibility.

Generate UUID in TypeScript

crypto.randomUUID()
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in TypeScript

The simplest way to generate a UUID in TypeScript is crypto.randomUUID() — available as a global in every modern browser and in Node.js 19+, or via an explicit node:crypto import on older Node versions. No install, no configuration. See the go uuid page for UUID primary keys in GORM and pgx with optimal PostgreSQL storage.

main.ts
// Browser or Node.js 19+ (global)
const id: `${string}-${string}-${string}-${string}-${string}` = crypto.randomUUID();
console.log(id);
// "550e8400-e29b-41d4-a716-446655440000"

// Node.js (explicit import, also works on 14.17+/16.17+)
import { randomUUID } from 'node:crypto';
const requestId = randomUUID();

Explanation

Convert a String to a UUID in TypeScript

A plain string type won't stop you from passing an arbitrary string where a UUID is expected. A branded (opaque) type fixes that — a common TypeScript pattern that adds compile-time safety with zero runtime cost. The best way to generate uuid python for Django models is uuid.uuid4 (without parentheses) as the default callable.

uuid.types.ts
type UUID = string & { readonly __brand: unique symbol };

const UUID_RE =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

function isValidUUID(value: string): boolean {
  return UUID_RE.test(value);
}

function toUUID(value: string): UUID {
  if (!isValidUUID(value)) {
    throw new Error(`Invalid UUID: ${value}`);
  }
  return value as UUID;
}

function isUUID(value: string): value is UUID {
  return isValidUUID(value);
}

// Usage
const userId: UUID = toUUID(crypto.randomUUID());

function getUser(id: UUID) {
  // ...
}

getUser(userId);         // OK
// getUser('not-a-uuid'); // Type error: string is not assignable to UUID

Explanation

Other Options for Generating UUIDs in TypeScript

crypto.randomUUID() only produces version 4 UUIDs. For v1, v5, and v7 with full type definitions, install the uuid package — its bundled types (or the separate @types/uuid package on older releases) cover every export.

terminal
npm install uuid
npm install --save-dev @types/uuid   # only needed on uuid < 9, which shipped without built-in types
uuid-example.ts
import { v4 as uuidv4, v5 as uuidv5, v7 as uuidv7, validate } from 'uuid';

type UUID = string & { readonly __brand: unique symbol };

const randomId: UUID = uuidv4() as UUID;
const sortableId: UUID = uuidv7() as UUID;

const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
const deterministicId: UUID = uuidv5('example.com', NAMESPACE) as UUID;

const idsByUser: Record<string, UUID> = {
  alice: randomId,
  bob: sortableId,
};

function assertUUID(value: string): asserts value is UUID {
  if (!validate(value)) {
    throw new Error(`Invalid UUID: ${value}`);
  }
}

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!