search

Home  >  Q&A  >  body text

How to generate GUID/UUID?

How to create a GUID (Globally Unique Identifier) ​​in JavaScript? GUIDs/UUIDs should be at least 32 characters long and should stay within the ASCII range to avoid trouble passing them.

I'm not sure what routines are available on all browsers, what the "randomness" of the built-in random number generator is, how it is seeded, etc.

P粉304704653P粉304704653432 days ago572

reply all(2)I'll reply

  • P粉352408038

    P粉3524080382023-10-09 14:12:19

    [Edited on March 5, 2023 to reflect the latest best practices for generating RFC4122-compliant UUIDs]

    crypto.randomUUID() is now standard on all modern browsers and JS runtimes. However, because new browser APIs are restricted to secure contexts, this method is only available to pages served locally (localhost or 127.0.0.1) or over HTTPS.

    For readers interested in other UUID versions, generating UUIDs on legacy platforms or in non-secure contexts, there is the uuid module. It is well-tested and supported.

    If the above method fails, there is also this method (based on the original answer to this question):

    function uuidv4() {
      return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
      );
    }
    
    console.log(uuidv4());

    Note: The use of any UUID generator that relies on Math.random() is strongly discouraged (including snippets featured in previous versions of this answer ) for reasons best explained here. TL;DR: solutions based on Math.random() do not provide good uniqueness guarantees.

    reply
    0
  • P粉190443691

    P粉1904436912023-10-09 13:09:03

    A UUID (Universally Unique Identifier), also known as a GUID (Globally Unique Identifier), according to RFC 4122 is an identifier designed to provide certain uniqueness guarantees.

    While it is possible to implement an RFC-compliant UUID with a few lines of JavaScript (e.g., see @broofa's answer , below) there are several common pitfalls:

    • Invalid id format (UUIDs must be of the form "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b]
    • Use of a low-quality source of randomness (such as Math.random)

    Therefore, developers writing code for production environments are encouraged to use strict, well-maintained implementations such as the uuid< /a> module.

    reply
    0
  • Cancelreply