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.
[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, becausenew browser APIs are restricted to secure contexts, this method is only available to pages served locally (localhost
or127.0.0.1
) or over HTTPS.For readers interested in other UUID versions, generating UUIDs on legacy platforms or in non-secure contexts, there isthe
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):
Note:The use ofanyUUID generator that relies on
Math.random()
is strongly discouraged(including snippets featured in previous versions of this answer ) forreasons best explained here.TL;DR:solutions based onMath.random()
do not provide good uniqueness guarantees.A UUID (Universally Unique Identifier), also known as a GUID (Globally Unique Identifier), according toRFC 4122is 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:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
", where x is one of [0-9, a-f]Mis one of [1-5], andNis [8, 9, a, or b]Math.random
)Therefore, developers writing code for production environments are encouraged to use strict, well-maintained implementations such as theuuid module.