Generating UUIDs in JavaScript
Serhii Shramko /
Have you ever needed to create unique identifiers in your JavaScript app? Say hello to window.crypto.randomUUID()
.
It's a great way to generate UUIDs in the browser.
What is it?
Simply put, window.crypto.randomUUID()
is a method that generates a
random v4 UUID. It's part of the Web Crypto API. It
provides cryptographically strong random values.
const myUUID = window.crypto.randomUUID();
console.log(myUUID); // Outputs something like '3b241101-e2bb-4255-8caf-4136c566a962'
Before using this function, check if it's available. Your code might run in different environments. I have a more detailed snippet on checking the environment if you want to dive deeper.
Why use it?
• Uniqueness: Guarantees that each UUID is unique across space and time.
• Security: Generates random values that are cryptographically strong.
• Convenience: No need to install external libraries; it’s built into modern browsers.
• Performance: Generates UUIDs with minimal overhead from extra code.