site logo

Ask. Code. Learn. Grow with the Developer Community.


Category: (All)
❮  Go Back

How to Generate a UUID or GUID in JavaScript (Best Practices for 2025)

Developers often need a way to create unique identifiers (UUIDs or GUIDs) in JavaScript for tasks like user sessions, database keys, or temporary file names.


A valid UUID should be globally unique, typically 32+ ASCII characters, and compliant with RFC4122 standards.


This raises two main questions:

  1. What is the best way to generate a UUID in JavaScript today?
  2. How can we ensure the result is cryptographically secure and browser-compatible?

Let’s explore the modern and legacy methods for creating GUIDs or UUIDs in JavaScript.

How to Generate a UUID or GUID in JavaScript Best Practices for 2025

coldshadow44 on 2025-10-15



1






Showing comments related to this post.

_coldshadow44

2025-10-15

1. Modern Solution: Use crypto.randomUUID()

The easiest and most reliable way to generate a UUID in JavaScript today is using the crypto.randomUUID() method.

It’s built into all modern browsers and JavaScript runtimes (like Node.js 19+), and produces RFC4122 version 4 UUIDs that look like this:

6f7b1e94-5b6f-42c3-b2b1-dc6d2b8a1f87


Example:

const id = crypto.randomUUID();
console.log(id); // Example output: "f6a9d6e4-82a3-4c88-8e45-7b1d9078bdb0"


✅ Pros:

  1. Follows the official RFC4122 v4 standard
  2. Uses a secure random source (crypto.getRandomValues())
  3. Native support in most browsers and Node.js environments


⚠️ Note:

crypto.randomUUID() only works in secure contexts — meaning pages served over HTTPS or from localhost.


2. For Older Browsers or Non-Secure Contexts

If you need a UUID generator that works in older environments or HTTP pages, use the uuid npm module, which provides consistent, RFC-compliant results across all platforms.

Installation (Node.js):

npm install uuid


Usage Example:

import { v4 as uuidv4 } from 'uuid';

const id = uuidv4();
console.log(id); // Example output: "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"

This library is widely used in production systems, supports multiple UUID versions, and is cryptographically strong.


3. Custom UUID Function (Fallback for Legacy Support)

If you can’t use external libraries or modern APIs, here’s a secure fallback that uses the browser’s crypto.getRandomValues() method:

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

console.log(uuidv4());

This compact function uses cryptographically strong random values to mimic a version 4 UUID.


4. Avoid Using Math.random()

While older code examples often used Math.random() to generate random IDs, this is no longer recommended.

Math.random() is not cryptographically secure and can produce collisions in large-scale applications.


Example of a weak method (❌ not recommended):

function weakUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}

This approach might appear to work, but it does not guarantee uniqueness or security.


Summary:

  1. Best method (modern): crypto.randomUUID()
  2. ⚙️ Best library (cross-platform): uuid npm module
  3. 🧩 Fallback (legacy-safe): uuidv4() using crypto.getRandomValues()
  4. Avoid: Any solution using Math.random()


Modern JavaScript makes generating unique, secure UUIDs simple and standardized — just use:

crypto.randomUUID();

for a one-line, reliable solution.




Member's Sites: