Understanding UUIDs in Node.js
Tags: node, webdev
Published: 2022-10-26 18:16:26

**Written by [Ukeje Goodness](https://blog.logrocket.com/author/ukejegoodness/)✏️**

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)](https://betterexplained.com/articles/the-quick-guide-to-guids/), 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?](#how-do-uuids-work)
*   [UUID length and collisions](#uuid-length-collisions)
*   [Generating UUIDs in Node.js](#generating-uuids-node-js)
    *   [Packages for generating UUIDs](#packages-generating-uuids)
        *   [The `uuid` package](#uuid-package)
        *   [The `short-uuid` package](#short-uuid-package)

## How do UUIDs work?

The IETF (Internet Engineering Task Force) defines the UUID protocol in [RFC 4122](https://tools.ietf.org/html/rfc4122) 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.

```javascript
uuidgen             // generates a UUID
uuidgen help        // view help for the UUID command.
```

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 <a name="uuid-length-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 <a name="generating-uuids-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.

```javascript
const crypto = require('crypto');
```

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

```javascript
let uuid = crypto.randomUUID();
console.log(uuid);
```

The code prints the generated UUID to the console. ![The Generated UUID Printed To The Console](https://blog.logrocket.com/wp-content/uploads/2022/09/generated-uuids-printed-console.png)

### Packages for generating UUIDs <a name="packages-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`](https://github.com/uuidjs/uuid) and [`short-uuid`](https://github.com/oculus42/short-uuid) packages.

#### The `uuid` package <a name="uuid-package">

The [`uuid` package](https://www.npmjs.com/package/uuid) 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](https://nodejs.org/en/docs/), [CommonJS](https://nodejs.org/api/modules.html), [Webpack](https://webpack.js.org/), [React Native Expo](https://docs.expo.dev/), and more. 

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

```bash
npm install uuid
```

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

```javascript
const uuid = require('uuid');
```

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

```javascript
const uuid4 = uuid.v4()
console.log(uuid4)
```

The `v4` method returns v4 UUIDs, and the code prints the UUID to the console. ![Version 4 UUIDs Printed To The Console](https://blog.logrocket.com/wp-content/uploads/2022/09/v4-uuid-package.png)

#### The `short-uuid` package <a name="short-uuid-package">

The [`short-uuid` package](https://www.npmjs.com/package/short-uuid) 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.

```javascript
npm install short-uuid
```

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

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

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

```javascript
console.log(short.uuid());
```

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 `base58`format by default.

```javascript
base58 = short.generate()
console.log(base58);
```

![Generating Short UUIDs Using The Generate Method](https://blog.logrocket.com/wp-content/uploads/2022/09/generating-short-uuids-generate-method.png) You can add additional arguments to your `short-uuid` package instance for extra functionalities. Adding distinct values will yield padded formats of the UUIDs.

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

const uuid = translator.generate()
console.log(uuid)
```

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.

```javascript
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
```

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](https://blog.logrocket.com/wp-content/uploads/2022/09/touuid-method-returns-original-uuid.png)

## 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](https://lp.logrocket.com/blg/signup).

[![LogRocket signup](https://blog.logrocket.com/wp-content/uploads/2019/12/network-request-filter-2-1.png)](https://lp.logrocket.com/blg/signup)

[LogRocket](https://lp.logrocket.com/blg/signup) 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](https://lp.logrocket.com/blg/signup).