A universally unique identifier (UUID) is a 128-bit character string you can use to label and access data. Using Node.js, you can easily create UUIDs using several approaches.

UUIDs are powerful for unique identification because the chances of encountering the same ID are very small. This also means you can generate a UUID autonomously without cross-checking against a central database. UUIDs are highly scalable.

Using the crypto Module

The built-in crypto module in Node provides the randomUUID() method to generate UUIDs.

        const crypto = require("crypto")
const uuid = crypto.randomUUID()

To prevent randomUUID() from using the cache during UUID generation, set disableEntropyCache to true, like this:

        const uuid = crypto.randomUUID({ disableEntropyCache: true })

Using the uuid Package

Unlike the crypto module, the uuid package is a third-party npm module. To install it, run the following command.

        npm install uuid

uuid allows you to generate different ID versions:

  • Version 1 and 4 generate a unique ID randomly generated.
  • Version 3 and 5 generate a unique ID from a namespace and name.

This example shows how you can generate a version 4 UUID:

        const {v4 : uuidv4} = require("uuid")
const id = uuidv4()

Using Nano ID

Nano ID is also another NPM package used to generate UUIDs in Node. While it works nearly the same as the uuid package, there are some differences:

  • The Nano ID contains 36 symbols instead of 21.
  • Nano ID is two times faster than uuid.
  • Nano ID is four times smaller than uuid. Its identifiers contain 130 bytes instead of 483 bytes.

Use the following code to generate a Nano ID:

        const { nanoid } = require("nanoid")
const id = nanoid()

Is Nano ID Better Than uuid?

There are at least three methods you can use to generate a UUID in Node: the built-in crypto module and the uuid and Nano ID third-party packages. If you want to use an external package, consider Nano ID. It is smaller and much faster than uuid.