Generate UUID v4 and v7 in TypeScript
Copy-paste TypeScript code that produces a UUID v4 (random, the long-standing default) or UUID v7 (time-ordered, the modern choice for database keys). Both blocks below are production-ready.
UUID v4 in TypeScript
v4 is purely random — 122 bits of entropy, no structure. Use it when you don't want timing information embedded in the ID, or when you don't care about index locality.
// TypeScript with strict mode — the Web Crypto API
// is fully typed in lib.dom.d.ts.
const id: string = crypto.randomUUID();
console.log(id);
UUID v7 in TypeScript
v7 embeds a millisecond Unix timestamp in the first 48 bits, so the IDs sort chronologically. This is what modern databases want from a primary key — sequential inserts land in adjacent index pages instead of scattering writes.
// Use the 'uuid' package with full type definitions.
// npm install uuid
import { v7 as uuidv7 } from 'uuid';
const id: string = uuidv7();
console.log(id);
Library support
The `uuid` package ships TypeScript types in v9.0.0+. Drop in, no `@types/uuid` needed (it's bundled).
Notes
`crypto.randomUUID()` returns a branded ``${string}-${string}-${string}-${string}-${string}`` template literal type when targeting recent lib versions, so downstream type narrowing works without casts.
Need them in bulk?
Our UUID generator produces 1 to 1000 UUIDs (v4 or v7) instantly, all in your browser, with one-click copy and JSON/CSV export. Useful for seeding test data or pre-generating IDs offline.