How to Generate a Global Unique Identifier (UUID) with JavaScript

A UUID (Universal Unique Identifier) is a string of characters that is guaranteed to be unique across all devices and time. UUIDs are widely used to uniquely identify resources such as database entries or files.

What exactly is a UUID?

A UUID is a string of characters that follows a predefined standard. A UUID is written in the following format:

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

Each x above represents a hexadecimal digit (0-9, a-f). The UUID is composed of 32 hexadecimal digits divided by hyphens into five parts.

There are several versions of UUIDs, but the most common is version 4.

Generating a UUID in JavaScript

In JavaScript, there are numerous ways to generate a UUID. The built-in Math.random() function may be used to produce random hexadecimal digits, which can then be concatenated to form the UUID string.

Generating a UUID using just Math.random()

The UUID is formed by concatenating 32 random hexadecimal digits generated by this function. The hyphens are then added to split the UUID into groups, as required by the UUID format.

function generateUUID() {
  // Generate random hexadecimal digits
  var digits = "0123456789abcdef";
  var n = digits.length;

  // Generate random hexadecimal digits and concatenate them to form the UUID
  var uuid = "";
  for (var i = 0; i < 32; i++) {
    uuid += digits[Math.floor(Math.random() * n)];
  }

  // Add hyphens to the UUID to separate it into groups
  uuid = uuid.substr(0, 8) + "-" + uuid.substr(8, 4) + "-" + uuid.substr(12, 4) + "-" + uuid.substr(16, 4) + "-" + uuid.substr(20, 12);

  return uuid;
}

Generating a UUID using the Current Time and Math.random()

This function creates a new JavaScript Date object and gets the current time in milliseconds since 1970/01/01. It then defines a string template with x's and y's as placeholders, which will be replaced with random hexadecimal digits created using Math.random().

function generateUUID() {
   // Get current time in milliseconds
   var d = new Date().getTime();

   // Define the UUID template with placeholder characters
   var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";

   // Replace the placeholders with random hexadecimal digits
   uuid = uuid.replace(/[xy]/g, function(c) {
       // Generate a random number between 0 and 15
       var r = (d + Math.random()*16)%16 | 0;

       // Update value of d for the next placeholder
       d = Math.floor(d/16);

       // Convert the number to a hexadecimal digit and return it
       return (c=="x" ? r : (r&0x3|0x8)).toString(16);
   });

   return uuid;
}

Generating a UUID using crypto.getRandomValues()

Another way to generate a UUID in JavaScript is to use the crypto module, which is available in modern browsers and Node.js. The crypto module provides a crypto.getRandomValues() function that generates cryptographically secure random values.

Here is an example of how to use the crypto module to generate a version 4 UUID:

function generateUUID() {
  // Use the crypto module to generate a random array of bytes
  var array = new Uint8Array(16);
  crypto.getRandomValues(array);

  // Convert the array of bytes to a hexadecimal string
  var uuid = "";
  for (var i = 0; i < array.length; i++) {
    uuid += array[i].toString(16).padStart(2, "0");
  }

  // Add hyphens to the UUID to separate it into groups
  uuid = uuid.substr(0, 8) + "-" + uuid.substr(8, 4) + "-" + uuid.substr(12, 4) + "-" + uuid.substr(16, 4) + "-" + uuid.substr(20, 12);

  return uuid;
}

Generating a UUID using crypto.randomUUID()

The crypto module also includes the crypto.randomUUID() method, which uses a cryptographically safe random number generator to produce a v4 UUID.

let uuid = crypto.randomUUID();

Generating a UUID using the uuid npm package

One of the preferred approaches is using a library called uuid to generate the v4 UUID:

npm install uuid
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

Conclusion

We looked at how to construct a Universal Unique Identifier (UUID) in JavaScript. We examined many approaches for generating UUIDs, including utilizing the built-in Math.random() function, the crypto module, and the existing uuid npm package.

Using Math.random() to produce a UUID is a simple and quick method, however the unpredictability of the UUID may not be adequate for some use cases, in which case you may add the current time to boost the uniqueness. Using the crypto module, on the other hand, provides a more safe and trustworthy approach to generate a UUID, but it is only accessible in modern browsers and Node.js.

Whichever approach you use, generating a UUID in JavaScript is a handy tool for uniquely identifying resources in your application.