DEV Community

Cover image for Understanding UUIDs in Node.js
Matt Angelosanto for LogRocket

Posted on • Originally published at blog.logrocket.com

Understanding UUIDs in Node.js

Written by Ukeje Goodness✏️

User identity and security are critical factors for building modern applications, and many measures are in place to ensure the security of users' identities.

One method of user identification on the internet is UUIDs, or universally unique identifiers. Similar to Microsoft’s GUIDs (globally unique identifiers), UUIDs are unique 128-bit values popularly used to uniquely identify entities on the internet.

In this article, you will learn about UUIDs, UUID collisions, and how to generate UUIDs in Node.js using three packages. To jump ahead:

How do UUIDs work?

The IETF (Internet Engineering Task Force) defines the UUID protocol in RFC 4122 as "A 128-bits-long identifier that can guarantee uniqueness across space and time."

The generation of different UUID versions occurs with different algorithms and methods. While v1 UUIDs use the timestamp and Mac address of the generating computer to identify, v4 UUIDs use random number generators depending on the website that is generating them.

Most operating systems have a CLI tool for generating UUIDs.

uuidgen             // generates a UUID
uuidgen help        // view help for the UUID command.
Enter fullscreen mode Exit fullscreen mode

The uuidgen command is available on Windows, Linux, and macOS systems to generate UUIDs on the command line or terminal.

You can use UUIDs in many areas of software development, from distributed applications, databases, networking, and scenarios where a higher degree of randomness is significant.

UUID length and collisions

Because the UUID protocol was designed to implement unique UUIDs, UUID collisions occur when two or more computers generate the same UUID.

Each UUID is distinct from other existing UUIDs, with a 0.00000006 collision probability and an estimated 85 years before the first case of collision (when there will be 2.71 quintillion UUIDs) if computers generate one billion UUIDs per second.

UUID collisions may be detrimental, primarily when used in the same case — for example, a UUID collision where the UUIDs are the primary keys in a database.

The standard length of generated UUIDs is 128 bits. However, you can shorten a UUID for various purposes, although this is not advised because shortening UUIDs increases the probability of collisions. In critical cases, shortening UUIDs may be detrimental to your application.

Generating UUIDs in Node.js

Most programming languages provide functionalities for generating UUIDs. In the Node.js runtime, the built-in crypto package has a randomUUID method for generating UUIDs.

First, import the crypto package into your JavaScript file.

const crypto = require('crypto');
Enter fullscreen mode Exit fullscreen mode

Calling the UUID method returns a UUID of standard length that you can use in your program.

let uuid = crypto.randomUUID();
console.log(uuid);
Enter fullscreen mode Exit fullscreen mode

The code prints the generated UUID to the console. The Generated UUID Printed To The Console

Packages for generating UUIDs

There are many external npm packages for generating UUIDs. The packages provide more functionalities than you’ll find in the crypto package.

Some popular npm packages for generating UUIDs in JavaScript are the uuid and short-uuid packages.

The uuid package

The uuid package provides functionality for generating cryptographically secure standard UUIDs with support for versions 1, 3, 4, and 5 UUIDs, as well as cross-platform support for Node.js, CommonJS, Webpack, React Native Expo, and more.

The UUID package is an external dependency, so you’ll have to install the package.

npm install uuid
Enter fullscreen mode Exit fullscreen mode

After installing the uuid package, import the package into your JavaScript file.

const uuid = require('uuid');
Enter fullscreen mode Exit fullscreen mode

Here’s an example of generating a v4 UUID with the uuid package.

const uuid4 = uuid.v4()
console.log(uuid4)
Enter fullscreen mode Exit fullscreen mode

The v4 method returns v4 UUIDs, and the code prints the UUID to the console. Version 4 UUIDs Printed To The Console

The short-uuid package

The short-uuid package provides functionalities for generating and translating RFC4122 v4-compliant standard UUIDs into shorter formats and versa. You can use the short-uuid package to generate v4 UUIDs and shorten them for your application’s use cases.

The short-uuid package is secure, with features like errors on incorrect UUIDs. By default, the short-uuid package returns shortened IDs of a consistent length, except if you specify a length, and the package shortens UUIDs by padding the alphabet characters.

Run this command in the terminal of your working directory to install the short-uuid package.

npm install short-uuid
Enter fullscreen mode Exit fullscreen mode

After installing the short-uuid package, you can import the package into your app.

const short = require('short-uuid');
Enter fullscreen mode Exit fullscreen mode

You can generate a simple, long UUID with the uuid method of your short-uuid instance.

console.log(short.uuid());
Enter fullscreen mode Exit fullscreen mode

The uuid method returns a UUID of standard length 128 bits.

You can generate shorter UUIDs with the generate method. The generate method returns a Flickr base58format by default.

base58 = short.generate()
console.log(base58);
Enter fullscreen mode Exit fullscreen mode

Generating Short UUIDs Using The Generate Method You can add additional arguments to your short-uuid package instance for extra functionalities. Adding distinct values will yield padded formats of the UUIDs.

// must not be duplicated
const translator = short("32814"); // Provide a specific alphabet for translation

const uuid = translator.generate()
console.log(uuid)
Enter fullscreen mode Exit fullscreen mode

The function will throw an error if there are duplicates in the alphabet values.

Here’s how you can shorten UUIDs and retrieve the original values with the short-uuid package.

const short = require('short-uuid');

const translator = short("342");

newUUID = translator.new()

original = translator.fromUUID(newUUID);

bits128 = translator.toUUID(original);

console.log(newUUID) // prints the generated UUID
console.log(original) // prints the original UUID
console.log(bits128) // prints reverted UUID of 128bits
Enter fullscreen mode Exit fullscreen mode

You generated a new UUID with the new method, an alias for the generate method that returns a padded UUID. The newUUID variable is the padded UUID generated by short-uuid, and the fromUUID method returns the original 128-bit UUID before padding. The toUUID method returns the originally generated UUID with the package. The ToUUID Method Returns The Original UUID

Conclusion

In this article, we explored UUIDs, UUID collisions, why you shouldn’t use short UUIDS, and how to generate UUIDs from your command line and JavaScript apps with the crypto package, uuid package, and short-uuid package.

UUIDs are useful for a wide range of use cases, and as you write more code, you’ll find more use cases for UUIDs in your apps.


200’s only Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, try LogRocket.

LogRocket signup

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.

Top comments (0)