How to generate a UUID
UUIDs provide a way to generate identifiers that are unlikely to collide and, as a result, can be generated in distributed systems without central coordination. The standard goes to great lengths to provide uniqueness by adding space and time locality alongside the randomness. Properly generated UUIDs have virtually no chance of collision.
Unfortunately, especially space locality requires the MAC address of the network card, and browsers have only limited access to the underlying hardware.
Random UUID
But meet the random UUID variant, which requires nothing else than a suitable random number generator. But keep in mind that a random UUID is not just 32 randomly generated hexadecimal numbers, as the version and the variant digits are fixed.
The format of such a UUID is:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
Where M is 4
, and N is between 8
and b
. There are other versions/variants too, but this combination is considered the random UUID.
Randomness
The randomness of the UUID depends on the quality of the underlying random generator. And, unfortunately, Math.random()
doesn't shine in this matter.
For a better source, use crypto.getRandomValue()
. It is guaranteed to be cryptographically secure, and also enjoys ubiquitous support from the browsers.
The script
To generate a valid and sufficiently random UUID, use this script:
function uuidv4() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}