Skip to main content
TS

How to Generate UUID in TypeScript

Using crypto.randomUUID()

How to Generate UUID in TypeScript. Call crypto.randomUUID() to generate a type-safe TypeScript UUID. When a project needs anything besides random values, a node.js uuid setup usually adds the standard npm package.

Generate UUID in TypeScript

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

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.

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. For a first data frame in RStudio, a r uuid walkthrough starts with a one-time CRAN install and a single function call.

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. If you need to generate uuid python that stays identical for the same input, name-based hashing with a namespace is the deterministic route.

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

About the author

Vinitha Pu

Founder and designer

Vinitha Pu is a graphic designer based in Palakkad, Kerala, who builds free, privacy-friendly browser tools. She studied Textile and Apparel Design at Avinashilingam University and completed a C-Tech in Graphic Design at Image Creative Education in 2025. She designs, builds and maintains the UUID generators, validator, decoder and the language and database UUID guides on UUID Generator.

  • Content author: Vinitha Pu
  • Fact checked by: Vinitha Pu. Every generator is checked against the RFC 4122 and RFC 9562 layouts and every code example is run before it goes live.
  • Published Updated

Vinitha Pu on Behance · Vinitha Pu on LinkedIn

Comments & Feedback

Share your experience or ask questions about this tool

Copied!