How to generate UUID in TypeScript

Generating UUID with the Crypto module

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

import crypto from 'crypto';

const myUuid = crypto.randomUUID();
console.log(myUuid);

The above code will output a random UUID, such as:

16f2e8d7-6d03-45c5-9aa2-9d20f1651de1

Generating UUID with the uuid package

The uuid package is another option for generating UUID in Typescript. This package provides several different functions for generating UUID, including Version 1, Version 4, and Version 5 UUID. To use the uuid package, you will need to install it first. You can do this using npm:

npm install uuid

Once the package is installed, you can use one of the provided functions to generate a UUID. Here is an example of how to use the v4() function to generate a Version 4 UUID:

import { v4 as uuidv4 } from 'uuid';
const myUuid = uuidv4();
console.log(myUuid);

The above code will output a random UUID, such as:

16f2e8d7-6d03-45c5-9aa2-9d20f1651de1

Using the uuid package can simplify the process of generating UUID in your TypeScript projects. You can find more information about the package in the package documentation.