How to create a universally unique identifier (UUID) in JavaScript

OpenJavaScript 0

Last updated: September 26, 2022.

A universally uniquer identifier (UUID) is a 36 character string (32 hex digits + 4 hypens) designed to have an extremely low probability of matching any previously produced UUID.

Here is what UUIDs look like:

483db10d-a28d-4c74-b7fb-8aee9993a03e

497c8e75-abe5-4fab-bcbd-c4c405944805

7b30bff9-2de9-44c8-a748-9a7b13d65cb5

The information contained in a UUID is dervied from timestamps, randomly generated values and information about the host system.

The rationale for generating UUIDs to a specified universal standard is that two indepedent databases can be combined with a standardized ID format and a practical probability of zero that two IDs will clash.

The probability of an ID clash is therefore not zero – but at the same time so unlikely that a UUID is often treated as if unique in practical situations.

To put this near-like zero probability in plain English: for the possibility of a single clash between two UUIDs to reaxh 50%, you would need to generate 1 billions UUIDs every second for the next century! (source: UUID Wikipedia entry).

Generating a UUID in JavaScript

For a long time, it was necessary to import a third-party library to generate UUIDs in JavaScript.

But since the introduction of the crypto module to the global window object, it is now possible to generate strongly random UUIDs natively.

Just call window.crypto.randomUUID() (or crypto.randomUUID() for short) anywhere in your script:

window.crypto.randomUUID();
// fd75e0c3-dcd3-42d6-b61f-cae59dca56ec

window.crypto.randomUUID(); 
// 31f1291a-9f74-4373-b720-6d902419ab92

window.crypto.randomUUID(); 
// 09c0d8ed-4aea-45f4-8e4f-5d46653e1914

The UUIDs this code produces are in the universally recognized format.

How to guarentee an ID is unique

Though the probability of clashing UUIDs is extremely low, it is not zero.

Unforunately, there is no way to create a global and decentralized ID distriution system that entirely avoids the possibility of an ID clash.

To guarentee the uniqueness of a UUID, a centralized distributor would have to keep track of all previously produced UUIDs to ensure that no duplicate is ever produced.

In the case of UUIDs, this would undermine one its main strengths: anyone can produce them locally on any machine. A centralized body would also create the potential for corruption.

But, on a smaller scale, you can guarentee that a UUID is unique to your app.

To do so, you must save all newly created UUIDs and then check newly created UUIDs against these for clashes.

Alternatively, you can create your own ID system that guarentees uniqueness by including a parameter containing the issue number for a particular ID. This would only be possible with JavaScript in Node.js, which would allow an issue number counter to be stored and updated on a server.

Related links