How to create a GUID / UUID

UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to RFC 4122, are identifiers designed to provide certain uniqueness guarantees.

While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (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)

Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the uuid module.

Leave a Comment