Helping you solve those tough coding problems!

Create GUID / UUID in JavaScript Create GUID / UUID in JavaScript

Published on Apr 9, 2019 by Jamie Munro

Most server-side languages and databases provide built-in support for UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier). At the time of writing JavaScript does not, so let's create our own UUID generator.




There are a few other examples out there that use random numbers and date parts; however, I found this solution that leverages window.crypto.getRandomValues. There are also of course of few libraries out there, most notably node-uuid, but sometimes it's fun to create things on our own for experimentation.

Using window.crypto.getRandomValues to create a UUID/GUID



Let's take a look at the function:


function uuid() {
  let bytes = window.crypto.getRandomValues(new Uint8Array(32));
  const randomBytes = () => (bytes = bytes.slice(1)) && bytes[0];

  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => 
      (c ^ randomBytes() & 15 >> c / 4).toString(16)
    );
}


Let's execute it 10 times and checkout the output:


for (var i = 0; i < 10; i++) {
  console.log(uuid());
}


When I ran it I received the following output:

1afe978d-420b-4820-b64b-0e22243b6652
779af4c2-3742-4695-9fc2-4d9fac9ecead
2a510685-17cb-466d-b2e3-54c3103ff8a2
e6e4eaec-aade-4143-a313-0589c8dfa3ab
5a6b74f6-e634-419b-91e3-7708dfdfd71f
449b9450-8fd5-4ca5-b6a1-7b618428e893
78b473a0-7cfa-45e2-9c7a-7edb1f8af949
0220e01a-3442-49ca-9e5d-7018b0c77617
62da3118-aecc-4405-be96-79f944d7039e
cf6de48b-99dd-4ebf-ae5d-0cd482292753

Looks pretty good to me. Let's run it again to see some more UUIDs:

5d272b50-5f04-400c-9e45-a8c3fe5d570b
7bc0eccb-5ef5-46ea-bd88-481a3a2b6618
90969df6-7979-4d38-a0ae-f94fd039151e
244b4515-f2de-4b17-81be-714259c0b598
da9e4edf-949b-4918-9485-244f510b3cf3
cdaeb4f2-164a-4436-8f37-02c287906ff1
a9d20c1d-6b6b-4ffa-8158-8dcc96bca078
28a6620d-3e0e-4789-b65b-ca8de0f351c2
41b9cec0-9754-4710-a817-b6bfbda73267
0cd58d8d-934e-41ea-91b8-ed8ecebdbe5d

I've previously accomplished this by executing a server-side function to generate a GUID and pass it through to my JavaScript. This saves me the awkwardness of passing a variable from the server to the client.

Tags: JavaScript | guid | uuid

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP