DEV Community

Jamund Ferguson
Jamund Ferguson

Posted on

4

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay