How to generate a version 4 UUID with Node.js

How to generate a version 4 UUID with Node.js

In this article, we will see how to generate a version 4 UUID using Node.js.

UUID (Universally Unique Identifier) ​​is a standard for unique identifiers commonly used in computer systems. UUID version 4 is particularly popular because it generates a random identifier based on randomly generated numbers. In this article, we will see how to generate a version 4 UUID using Node.js.

The easiest way to generate a v4 UUID in Node.js is to use the uuid package, which provides a complete implementation of UUIDs. First, we need to install the package.


npm install uuid

Once the package is installed, you can use it to generate a v4 UUID. Here's how to do it:


// Import the uuid module
const { v4: uuidv4 } = require('uuid');

// Generate a v4 UUID
const uuid = uuidv4();

// Print the generated UUID
console.log('UUID Version 4:', uuid);

In the code above:

  • Importing the module: We import the v4 function from the uuid package and rename it to uuidv4 for easier readability.
  • Generating the UUID: We call the uuidv4() function to generate a new version 4 UUID.
  • Printing the UUID: We use console.log to print the generated UUID.

V4 UUIDs are useful when you need unique identifiers without having to rely on a centralized sequence or incremental numbering system. They are widely used in databases, configuration files, and as resource identifiers.

Conclusion

Generating a version 4 UUID in Node.js is easy with the uuid package. With just a few lines of code, you can create unique identifiers and use them in your project. This technique is especially useful in contexts where unique identifiers are crucial, such as in resource management or distributed databases.