Home >Web Front-end >JS Tutorial >How to Generate UUIDs in JavaScript: Best Practices and Fallback Methods?

How to Generate UUIDs in JavaScript: Best Practices and Fallback Methods?

Linda Hamilton
Linda HamiltonOriginal
2025-01-03 10:11:42794browse

How to Generate UUIDs in JavaScript: Best Practices and Fallback Methods?

UUID Generation in JavaScript: Options and Best Practices

Creating globally-unique identifiers (UUIDs) in JavaScript is a common requirement in various applications. This article explores the available options and recommends best practices for generating UUIDs.

Modern Browsers and JS Runtimes: crypto.randomUUID()

For modern browsers and JS runtimes, crypto.randomUUID() is the recommended method. It follows RFC4122 standards and produces UUIDs that are secure and compliant. However, this method is only available to pages served over HTTPS or in secure contexts.

Other UUID Versions and Legacy Platforms: uuid Module

If you need UUIDs in other versions or on legacy platforms, the uuid module is a reliable option. It is well-tested and supports various UUID versions.

Fallback Method for Non-Secure Contexts

For cases where secure contexts like HTTPS are not feasible, a robust fallback method is available:

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

This method utilizes the crypto.getRandomValues() function to generate random numbers for UUID generation in non-secure contexts. It ensures the UUIDs remain within the ASCII range for seamless interoperability.

The above is the detailed content of How to Generate UUIDs in JavaScript: Best Practices and Fallback Methods?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn