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"
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);
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);
Work with our skilled Javascript developers to accelerate your project and boost its performance.
Hire JavaScript Developers