DEV Community

Jamund Ferguson
Jamund Ferguson

Posted on

Generating Universally Unique Identifiers with JavaScript

For as long as I can remember the recommended way to generate unique universal Identifiers in node.js was to the uuid module. These IDs are useful in all sorts of scenarios including for database keys, filenames, URLs, etc. Recently both node.js and the browser began offering nearly identical APIs that will generate 36-character version 4 uuids without any dependencies.

Available in Chrome since July 2021 and coming soon other browsers is crypto.randomUUID(). There's a global crypto object that's available on the global self property. You can use that to generate a UUID like this:

self.crypto.randomUUID();
Enter fullscreen mode Exit fullscreen mode

The UUID it generates is a v4 UUID per the spec and ends up with a string that looks something like this:

"0aa9d4f3-efdb-4a06-806c-5f8fa5f1767d"
Enter fullscreen mode Exit fullscreen mode

Browser Compatability for randomUUID

You want to do the same thing in node? Instead of reaching for the uuid package. As long as you're on version 14.17 or newer, you can do this:

const { randomUUID } = require("crypto");
randomUUID(); // "0aa9d4f3-efdb-4a06-806c-5f8fa5f1767d"
Enter fullscreen mode Exit fullscreen mode

It's cool see node and the browser adopting powerful APIs for crypto and improved randomness. I'll definitely be reaching for these in the near future!


You can read more in the WebCrypto section in the MDN or the crypto section in the node.js docs.

Discussion (0)