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.
// 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
crypto.randomUUID()is available as a global in browsers and Node.js 19+; on older Node (14.17+/16.17+) importrandomUUIDfromnode:cryptoinstead.- TypeScript's DOM types (and recent
@types/node) type the return value as a template literal of five hyphen-joined string segments rather than a barestring, so the compiler can distinguish it from an arbitrary string — though it still doesn't validate the actual hex content. - No package install or bundler configuration is required, since it's a runtime global backed by your OS's cryptographically secure random number generator.
- The generated value is version 4 (random) only — for other versions see the
uuidpackage below.
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.
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
type UUID = string & { readonly __brand: unique symbol }is just astringat runtime, but TypeScript treats it as incompatible with a plainstringunless it's explicitly cast.isValidUUID()checks the value against the standard UUID pattern — 36 characters, version and variant nibbles included — before anything is trusted.toUUID()is the only sanctioned way to produce aUUID-typed value; it throws on invalid input, so a variable typedUUIDis guaranteed to have passed validation at least once.- This is one common approach to nominal typing in TypeScript, not a language feature — libraries like
zodandio-tsoffer more elaborate variants of the same idea.
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.
npm install uuid
npm install --save-dev @types/uuid # only needed on uuid < 9, which shipped without built-in types
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
uuidversion 9 and later ships its own TypeScript types, so a separate@types/uuidinstall is only needed on uuid 8 and earlier.uuidv7()(added in uuid 9.1) generates a Unix-timestamp-based, sortable UUID — useful for database primary keys where insertion order matters.uuidv5(name, namespace)is deterministic: the same name and namespace always produce the same UUID, so you can derive a stable ID instead of storing one.- Casting each result
as UUIDre-applies the branded type from the previous section, keeping the same compile-time guarantees whether the ID came fromcrypto.randomUUID()or theuuidpackage.