# Generate a random UUID

Return a version 4 UUID from the platform’s cryptographic generator.

Canonical: https://1loc.dev/random/generate-a-random-uuid/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Usage lines executed in Node.js 22 and headless Chromium; no external services
Updated: 2026-10-28

## Implementation

```javascript
function uuid() { return crypto.randomUUID(); }
```

## Usage

```javascript
const key = uuid();
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(key); // → true
key.length; // → 36
```

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

## Limits

- crypto.randomUUID() returns an RFC 9562 version 4 UUID. In browsers it requires a secure context: HTTPS or localhost.
- The original built UUIDs from Math.random, which is not a cryptographic generator.
- As an idempotency key, create the UUID once per operation and store it with the operation: a new UUID on every retry defeats deduplication. Oveyon accepts Idempotency-Key values of 1–190 characters; see Build an idempotency key.

The function does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/generate-a-random-uuid.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: w3bdesign
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Uses crypto.randomUUID() instead of Math.random. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
