How to generate UUIDs in JavaScript

Generating UUIDs in JavaScript using the Crypto module

One way to generate UUIDs in JavaScript is to use the built-in Crypto module. As of Node.js version 14.17.0, the Crypto module includes a new method called crypto.randomUUID(). This method can be used to directly generate a version 4 UUID. Here is an example:

const crypto = require('crypto');

const uuid = crypto.randomUUID();

Generating UUIDs in JavaScript using the uuid package

Another way to generate UUIDs in JavaScript is to use the uuid package. This package provides a simple and convenient API for generating UUIDs of various versions, and can be used on both the client and server sides of a JavaScript application.

To use the uuid package, you first need to install it using the npm or yarn package manager:

npm install uuid

Once you have installed the package, you can import it into your code:

import { v4 as uuidv4 } from 'uuid';

Here, we are importing the v4 method from the uuid package, which generates Version 4 UUIDs.

To generate a UUID, simply call the uuidv4() method:

const myUUID = uuidv4();

This will output a randomly generated UUID Version 4.

The uuid package also provides methods for generating other types of UUIDs, such as Version 1 and Version 5 UUIDs. You can find more information about these methods in the package documentation.

Using this package really can simplify the process of generating UUIDs in your JavaScript projects.