To create a GUID/UUID in JavaScript, the best practice is to use the crypto.randomUUID() method. This is the recommended approach for modern browsers and JavaScript runtimes because it generates a cryptographically secure, RFC4122-compliant UUID. However, keep in mind that this method only works in secure contexts (HTTPS or localhost).

JavaScript

// Creates a cryptographically-strong random UUID
const uuid = crypto.randomUUID();
console.log(uuid); // e.g., "36b8f84d-df4e-4d49-b662-bcde71a8764f"

Fallback Method

If you need to support older browsers or non-secure contexts where crypto.randomUUID() is not available, you can use the following function, which utilizes crypto.getRandomValues() for random number generation:

JavaScript

function createUUID() {
  return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}

const uuid = createUUID();
console.log(uuid);

Using a Library

For broader compatibility and more features, you can also use a library like uuid. This is a popular, well-tested module that provides a reliable way to generate UUIDs.
First, install the library using npm:

Bash
npm install uuid

Then, you can use it in your code:
JavaScript
import { v4 as uuidv4 } from 'uuid';

const uuid = uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
console.log(uuid);

Important Considerations

  • Avoid Math.random(): It is strongly advised not to use any method that relies on Math.random() for generating UUIDs. This is because Math.random() does not provide strong guarantees of uniqueness and is not suitable for production environments where collision resistance is important.
  • URL.createObjectURL(): Another interesting, albeit less common, method is to use URL.createObjectURL(new Blob()). This will generate a URL containing a UUID that you can then extract. While this is guaranteed to produce a unique ID, its performance may be a factor to consider for your specific use case.

Need Help With Javascript Development?

Work with our skilled Javascript developers to accelerate your project and boost its performance.

Hire JavaScript Developers

Support On Demand!

Related Q&A