blob: 83ae737eb9314373b5a7cd982f129bc7b3654810 [file] [log] [blame] [view]
Benedikt Meurer96faaf22025-02-27 09:22:331<!--
2 -- This file is auto-generated from README_js.md. Changes should be made there.
3 -->
4
5# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions/workflows/browser.yml)
6
7For the creation of [RFC9562](https://www.rfc-editor.org/rfc/rfc9562.html) (formerly [RFC4122](https://www.rfc-editor.org/rfc/rfc4122.html)) UUIDs
8
9- **Complete** - Support for all RFC9562 UUID versions
10- **Cross-platform** - Support for...
11 - ESM & Common JS
12 - [Typescript](#support)
13 - [Chrome, Safari, Firefox, and Edge](#support)
14 - [NodeJS](#support)
15 - [React Native / Expo](#react-native--expo)
16- **Secure** - Uses modern `crypto` API for random values
17- **Compact** - Zero-dependency, [tree-shakable](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking)
18- **CLI** - [`uuid` command line](#command-line) utility
19
20<!-- prettier-ignore -->
21> [!NOTE]
22> `uuid@11` is now available: See the [CHANGELOG](./CHANGELOG.md) for details. TL;DR:
23> * TypeScript support is now included (remove `@types/uuid` from your dependencies)
24> * Subtle changes to how the `options` arg is interpreted for `v1()`, `v6()`, and `v7()`. [See details](#options-handling-for-timestamp-uuids)
25> * Binary UUIDs are now `Uint8Array`s. (May impact callers of `parse()`, `stringify()`, or that pass an `option#buf` argument to `v1()`-`v7()`.)
26
27## Quickstart
28
29**1. Install**
30
31```shell
32npm install uuid
33```
34
35**2. Create a UUID**
36
37ESM-syntax (must use named exports):
38
39```javascript
40import { v4 as uuidv4 } from 'uuid';
41uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
42```
43
44... CommonJS:
45
46```javascript
47const { v4: uuidv4 } = require('uuid');
48uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
49```
50
51For timestamp UUIDs, namespace UUIDs, and other options read on ...
52
53## API Summary
54
55| | | |
56| --- | --- | --- |
57| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `[email protected]` |
58| [`uuid.MAX`](#uuidmax) | The max UUID string (all ones) | New in `[email protected]` |
59| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `[email protected]` |
60| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `[email protected]` |
61| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | |
62| [`uuid.v1ToV6()`](#uuidv1tov6uuid) | Create a version 6 UUID from a version 1 UUID | New in `uuid@10` |
63| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | |
64| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | |
65| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | |
66| [`uuid.v6()`](#uuidv6options-buffer-offset) | Create a version 6 (timestamp, reordered) UUID | New in `uuid@10` |
67| [`uuid.v6ToV1()`](#uuidv6tov1uuid) | Create a version 1 UUID from a version 6 UUID | New in `uuid@10` |
68| [`uuid.v7()`](#uuidv7options-buffer-offset) | Create a version 7 (Unix Epoch time-based) UUID | New in `uuid@10` |
69| ~~[`uuid.v8()`](#uuidv8)~~ | "Intentionally left blank" | |
70| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `[email protected]` |
71| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `[email protected]` |
72
73## API
74
75### uuid.NIL
76
77The nil UUID string (all zeros).
78
79Example:
80
81```javascript
82import { NIL as NIL_UUID } from 'uuid';
83
84NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000'
85```
86
87### uuid.MAX
88
89The max UUID string (all ones).
90
91Example:
92
93```javascript
94import { MAX as MAX_UUID } from 'uuid';
95
96MAX_UUID; // ⇨ 'ffffffff-ffff-ffff-ffff-ffffffffffff'
97```
98
99### uuid.parse(str)
100
101Convert UUID string to array of bytes
102
103| | |
104| --------- | ---------------------------------------- |
105| `str` | A valid UUID `String` |
106| _returns_ | `Uint8Array[16]` |
107| _throws_ | `TypeError` if `str` is not a valid UUID |
108
109<!-- prettier-ignore -->
110> [!NOTE]
111> Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below.
112
113Example:
114
115```javascript
116import { parse as uuidParse } from 'uuid';
117
118// Parse a UUID
119uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨
120// Uint8Array(16) [
121// 110, 192, 189, 127, 17,
122// 192, 67, 218, 151, 94,
123// 42, 138, 217, 235, 174,
124// 11
125// ]
126```
127
128### uuid.stringify(arr[, offset])
129
130Convert array of bytes to UUID string
131
132| | |
133| -------------- | ---------------------------------------------------------------------------- |
134| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. |
135| [`offset` = 0] | `Number` Starting index in the Array |
136| _returns_ | `String` |
137| _throws_ | `TypeError` if a valid UUID string cannot be generated |
138
139<!-- prettier-ignore -->
140> [!NOTE]
141> Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below.
142
143Example:
144
145```javascript
146import { stringify as uuidStringify } from 'uuid';
147
148const uuidBytes = Uint8Array.of(
149 0x6e,
150 0xc0,
151 0xbd,
152 0x7f,
153 0x11,
154 0xc0,
155 0x43,
156 0xda,
157 0x97,
158 0x5e,
159 0x2a,
160 0x8a,
161 0xd9,
162 0xeb,
163 0xae,
164 0x0b
165);
166
167uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'
168```
169
170### uuid.v1([options[, buffer[, offset]]])
171
172Create an RFC version 1 (timestamp) UUID
173
174| | |
175| --- | --- |
176| [`options`] | `Object` with one or more of the following properties: |
177| [`options.node = (random)` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) |
178| [`options.clockseq = (random)`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff |
179| [`options.msecs = (current time)`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) |
180| [`options.nsecs = 0`] | RFC "timestamp" field (`Number` of nanoseconds to add to `msecs`, should be 0-10,000) |
181| [`options.random = (random)`] | `Array` of 16 random bytes (0-255) used to generate other fields, above |
182| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) |
183| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` |
184| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
185| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
186| _throws_ | `Error` if more than 10M UUIDs/sec are requested |
187
188<!-- prettier-ignore -->
189> [!NOTE]
190> The default [node id](https://datatracker.ietf.org/doc/html/rfc9562#section-5.1) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process.
191
192<!-- prettier-ignore -->
193> [!NOTE]
194> `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields.
195
196Example:
197
198```javascript
199import { v1 as uuidv1 } from 'uuid';
200
201uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-9bdd-2b0d7b3dcb6d'
202```
203
204Example using `options`:
205
206```javascript
207import { v1 as uuidv1 } from 'uuid';
208
209const options = {
210 node: Uint8Array.of(0x01, 0x23, 0x45, 0x67, 0x89, 0xab),
211 clockseq: 0x1234,
212 msecs: new Date('2011-11-01').getTime(),
213 nsecs: 5678,
214};
215uuidv1(options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'
216```
217
218### uuid.v1ToV6(uuid)
219
220Convert a UUID from version 1 to version 6
221
222```javascript
223import { v1ToV6 } from 'uuid';
224
225v1ToV6('92f62d9e-22c4-11ef-97e9-325096b39f47'); // ⇨ '1ef22c49-2f62-6d9e-97e9-325096b39f47'
226```
227
228### uuid.v3(name, namespace[, buffer[, offset]])
229
230Create an RFC version 3 (namespace w/ MD5) UUID
231
232API is identical to `v5()`, but uses "v3" instead.
233
234<!-- prettier-ignore -->
235> [!IMPORTANT]
236> Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_."
237
238### uuid.v4([options[, buffer[, offset]]])
239
240Create an RFC version 4 (random) UUID
241
242| | |
243| --- | --- |
244| [`options`] | `Object` with one or more of the following properties: |
245| [`options.random`] | `Array` of 16 random bytes (0-255) |
246| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) |
247| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` |
248| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
249| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
250
251Example:
252
253```javascript
254import { v4 as uuidv4 } from 'uuid';
255
256uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
257```
258
259Example using predefined `random` values:
260
261```javascript
262import { v4 as uuidv4 } from 'uuid';
263
264const v4options = {
265 random: Uint8Array.of(
266 0x10,
267 0x91,
268 0x56,
269 0xbe,
270 0xc4,
271 0xfb,
272 0xc1,
273 0xea,
274 0x71,
275 0xb4,
276 0xef,
277 0xe1,
278 0x67,
279 0x1c,
280 0x58,
281 0x36
282 ),
283};
284uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836'
285```
286
287### uuid.v5(name, namespace[, buffer[, offset]])
288
289Create an RFC version 5 (namespace w/ SHA-1) UUID
290
291| | |
292| --- | --- |
293| `name` | `String \| Array` |
294| `namespace` | `String \| Array[16]` Namespace UUID |
295| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` |
296| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
297| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
298
299<!-- prettier-ignore -->
300> [!NOTE]
301> The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`.
302
303Example with custom namespace:
304
305```javascript
306import { v5 as uuidv5 } from 'uuid';
307
308// Define a custom namespace. Readers, create your own using something like
309// https://www.uuidgenerator.net/
310const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
311
312uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'
313```
314
315Example with RFC `URL` namespace:
316
317```javascript
318import { v5 as uuidv5 } from 'uuid';
319
320uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1'
321```
322
323### uuid.v6([options[, buffer[, offset]]])
324
325Create an RFC version 6 (timestamp, reordered) UUID
326
327This method takes the same arguments as uuid.v1().
328
329```javascript
330import { v6 as uuidv6 } from 'uuid';
331
332uuidv6(); // ⇨ '1e940672-c5ea-64c0-9b5d-ab8dfbbd4bed'
333```
334
335Example using `options`:
336
337```javascript
338import { v6 as uuidv6 } from 'uuid';
339
340const options = {
341 node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
342 clockseq: 0x1234,
343 msecs: new Date('2011-11-01').getTime(),
344 nsecs: 5678,
345};
346uuidv6(options); // ⇨ '1e1041c7-10b9-662e-9234-0123456789ab'
347```
348
349### uuid.v6ToV1(uuid)
350
351Convert a UUID from version 6 to version 1
352
353```javascript
354import { v6ToV1 } from 'uuid';
355
356v6ToV1('1ef22c49-2f62-6d9e-97e9-325096b39f47'); // ⇨ '92f62d9e-22c4-11ef-97e9-325096b39f47'
357```
358
359### uuid.v7([options[, buffer[, offset]]])
360
361Create an RFC version 7 (random) UUID
362
363| | |
364| --- | --- |
365| [`options`] | `Object` with one or more of the following properties: |
366| [`options.msecs = (current time)`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) |
367| [`options.random = (random)`] | `Array` of 16 random bytes (0-255) used to generate other fields, above |
368| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) |
369| [`options.seq = (random)`] | 32-bit sequence `Number` between 0 - 0xffffffff. This may be provided to help ensure uniqueness for UUIDs generated within the same millisecond time interval. Default = random value. |
370| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` |
371| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
372| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
373
374Example:
375
376```javascript
377import { v7 as uuidv7 } from 'uuid';
378
379uuidv7(); // ⇨ '01695553-c90c-705a-b56d-778dfbbd4bed'
380```
381
382### ~~uuid.v8()~~
383
384**_"Intentionally left blank"_**
385
386<!-- prettier-ignore -->
387> [!NOTE]
388> Version 8 (experimental) UUIDs are "[for experimental or vendor-specific use cases](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-8)". The RFC does not define a creation algorithm for them, which is why this package does not offer a `v8()` method. The `validate()` and `version()` methods do work with such UUIDs, however.
389
390### uuid.validate(str)
391
392Test a string to see if it is a valid UUID
393
394| | |
395| --------- | --------------------------------------------------- |
396| `str` | `String` to validate |
397| _returns_ | `true` if string is a valid UUID, `false` otherwise |
398
399Example:
400
401```javascript
402import { validate as uuidValidate } from 'uuid';
403
404uuidValidate('not a UUID'); // ⇨ false
405uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true
406```
407
408Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds.
409
410```javascript
411import { version as uuidVersion } from 'uuid';
412import { validate as uuidValidate } from 'uuid';
413
414function uuidValidateV4(uuid) {
415 return uuidValidate(uuid) && uuidVersion(uuid) === 4;
416}
417
418const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210';
419const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836';
420
421uuidValidateV4(v4Uuid); // ⇨ true
422uuidValidateV4(v1Uuid); // ⇨ false
423```
424
425### uuid.version(str)
426
427Detect RFC version of a UUID
428
429| | |
430| --------- | ---------------------------------------- |
431| `str` | A valid UUID `String` |
432| _returns_ | `Number` The RFC version of the UUID |
433| _throws_ | `TypeError` if `str` is not a valid UUID |
434
435Example:
436
437```javascript
438import { version as uuidVersion } from 'uuid';
439
440uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1
441uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4
442```
443
444<!-- prettier-ignore -->
445> [!NOTE]
446> This method returns `0` for the `NIL` UUID, and `15` for the `MAX` UUID.
447
448## Command Line
449
450UUIDs can be generated from the command line using `uuid`.
451
452```shell
453$ npx uuid
454ddeb27fb-d9a0-4624-be4d-4615062daed4
455```
456
457The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details:
458
459```shell
460$ npx uuid --help
461
462Usage:
463 uuid
464 uuid v1
465 uuid v3 <name> <namespace uuid>
466 uuid v4
467 uuid v5 <name> <namespace uuid>
468 uuid v7
469 uuid --help
470
471Note: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs
472defined by RFC9562
473```
474
475## `options` Handling for Timestamp UUIDs
476
477Prior to `uuid@11`, it was possible for `options` state to interfere with the internal state used to ensure uniqueness of timestamp-based UUIDs (the `v1()`, `v6()`, and `v7()` methods). Starting with `uuid@11`, this issue has been addressed by using the presence of the `options` argument as a flag to select between two possible behaviors:
478
479- Without `options`: Internal state is utilized to improve UUID uniqueness.
480- With `options`: Internal state is **NOT** used and, instead, appropriate defaults are applied as needed.
481
482## Support
483
484**Browsers**: `uuid` [builds are tested](/uuidjs/uuid/blob/main/wdio.conf.js) against the latest version of desktop Chrome, Safari, Firefox, and Edge. Mobile versions of these same browsers are expected to work but aren't currently tested.
485
486**Node**: `uuid` [builds are tested](https://github.com/uuidjs/uuid/blob/main/.github/workflows/ci.yml#L26-L27) against node ([LTS releases](https://github.com/nodejs/Release)), plus one prior. E.g. `node@18` is in maintainence mode, and `node@22` is the current LTS release. So `uuid` supports `node@16`-`node@22`.
487
488**Typescript**: TS versions released within the past two years are supported. [source](https://github.com/microsoft/TypeScript/issues/49088#issuecomment-2468723715)
489
490## Known issues
491
492<!-- This header is referenced as an anchor in src/rng-browser.ts -->
493
494### "getRandomValues() not supported"
495
496This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill:
497
498#### React Native / Expo
499
5001. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme)
5011. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point:
502
503```javascript
504import 'react-native-get-random-values';
505import { v4 as uuidv4 } from 'uuid';
506```
507
508---
509
510Markdown generated from [README_js.md](README_js.md) by <a href="https://github.com/broofa/runmd"><image height="13" src="https://camo.githubusercontent.com/5c7c603cd1e6a43370b0a5063d457e0dabb74cf317adc7baba183acb686ee8d0/687474703a2f2f692e696d6775722e636f6d2f634a4b6f3662552e706e67" /></a>