DEV Community

Cover image for Generate a Universally Unique Identifier (uuid) with Node.js
James Edwards
James Edwards

Posted on • Edited on • Originally published at devextent.com

Generate a Universally Unique Identifier (uuid) with Node.js

The uuid, or universally unique identifier, npm package is a secure way to generate cryptographically strong unique identifiers with Node.js that doesn't require a large amount of code. The uuid npm package has zero dependencies, and over thirty thousand packages depend on it, making it a safe choice when an id is needed that is guaranteed to be unique. It supports commonJS modules and also ECMAScript Modules, making it a good cross-platform choice. Besides generating a unique id, the uuid npm package has other utility methods available in its API that can be useful when working with unique identifiers, to ensure that they are valid.

npm install uuid

We can create a sample node.js script to test out the functionality of the uuid npm package, but first make sure that Node.js and npm are installed. Then run the command npm init in a test project folder terminal window, and follow the prompts that are shown. This will create a package.json file, which will be used to install the uuid package. Creating a package.json file is not needed, if you are adding uuid to an existing project.

After creating the package.json file run the command npm install uuid --save, and the uuid npm package will be added to the node_modules folder inside the project folder. If you are using TypeScript you can also run the command npm install @types/uuid to install the type definitions for the uuid npm package. See how to compile TypeScript with npm for more information if you want to use the uuid npm package with TypeScript.

Generate uuid with Node.js

With the uuid npm package installed we can now import it into a Node.js script and use the functions provided. Create a new file named "index.js" and include the uuid npm package like this:

import { v4 as uuidv4 } from "uuid";

function main() {
  const uniqueId = uuidv4();
  console.log(uniqueId);
}

main();
Enter fullscreen mode Exit fullscreen mode

What this does is import the RFC4122 version 4 uuid export using ECMAScript modules syntax. If you aren't using ES Modules, you can by following the steps to import and export ES Modules in Node.js, or you can use commonJS modules with a different import syntax that looks like this:

const { v4: uuidv4 } = require("uuid");
Enter fullscreen mode Exit fullscreen mode

For the remainder of this example we will use the ES Module syntax.

To test out the Node.js script, we can add a package.json script to run it. In the "scripts" property of the package.json file add the following:

{
  "scripts": {
    "start": "node index.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

After adding the additional script run the command npm run start, and you should see a uuid output to the console that looks similar to this:

d160b410-e6a8-4cbb-92c2-068112187503
Enter fullscreen mode Exit fullscreen mode

You can re-run the command and a new uuid will be generated each time.

Validate uuid

The uuid npm package can also validate uuid strings to test whether they are a valid uuid. To do this add some additional code to the index.js file we just created.

import { v4 as uuidv4 } from "uuid";
import { validate as uuidValidate } from "uuid";

function main() {
  const uniqueId = uuidv4();
  console.log(uniqueId);

  const isValid = uuidValidate(uniqueId);
  console.log(isValid);
}

main();
Enter fullscreen mode Exit fullscreen mode

Then run the npm run start command again and you will see the result of the uuidValidate method is output as true. If the value passed into the uuidValidate function is not a valid uuid the output will be false.

Detect uuid RFC version

After validation, if we have a valid uuid, the uuid npm package can also detect the version of a uuid string. Building off the index.js sample code add another import to access the uuid version function and test the uniqueId that is generated like this:

import { v4 as uuidv4 } from "uuid";
import { validate as uuidValidate } from "uuid";
import { version as uuidVersion } from "uuid";

function main() {
  const uniqueId = uuidv4();
  console.log(uniqueId);

  const isValid = uuidValidate(uniqueId);
  console.log(isValid);

  const version = uuidVersion(uniqueId);
  console.log(version);
}

main();
Enter fullscreen mode Exit fullscreen mode

Now when we run the index.js script we can see the version of the uniqueId that is generated is output as "4", matching the uuidv4 version we imported initially. If the uuidVersion function is not passed a valid uuid an error will be thrown, so it can be helpful to wrap this function in a try/catch block to capture any errors.

import { v4 as uuidv4 } from "uuid";
import { validate as uuidValidate } from "uuid";
import { version as uuidVersion } from "uuid";

function main() {
  const uniqueId = uuidv4();
  console.log(uniqueId);

  const isValid = uuidValidate(uniqueId);
  console.log(isValid);

  try {
    const version = uuidVersion(uniqueId);
    console.log(version);
  } catch (error) {
    console.log(error);
  }
}

main();
Enter fullscreen mode Exit fullscreen mode

This way any resulting error can be output to the console, or handled in a way that is best for the current usage.

Generate NIL uuid

If you need to generate a NIL uuid, or a uuid that is entirely zeros, the uuid npm package provides the NIL_UUID as an export. Adding it to the index.js sample script looks like this:

import { v4 as uuidv4 } from "uuid";
import { validate as uuidValidate } from "uuid";
import { version as uuidVersion } from "uuid";
import { NIL as NIL_UUID } from "uuid";

function main() {
  const uniqueId = uuidv4();
  console.log(uniqueId);

  const isValid = uuidValidate(uniqueId);
  console.log(isValid);

  try {
    const version = uuidVersion(uniqueId);
    console.log(version);
  } catch (error) {
    console.log(error);
  }

  console.log(NIL_UUID);
}

main();
Enter fullscreen mode Exit fullscreen mode

I haven't come across a use case where a NIL uuid is needed, but it is provided in the uuid npm package so I'm sure there are plenty.

The uuid npm package is a helpful utility to generate a unique id with Node.js that saves a lot of the potential headache from generating one from scratch, while also ensuring the value are unique, secure, and matching a specific RFC version.

Top comments (2)

Collapse
 
jaylandro profile image
Jay Landro

How does this compare to crypto.randomBytes(16)? Is the uuid package using the same internals? Or is the benefit the validate and version helpers that come with uuid?

Collapse
 
jdedwards3 profile image
James Edwards

The uuidv4 package will generate in the RFC4122 format