NodeJS - crypto.randomUUID() Method


The NodeJs Crypto randomUUID() method is used to to generate a version 4 UUID using a cryptographically secure random number generator. This feature is only accessible in secure contexts, such as HTTPS, in certain supported browsers.

In NodeJS, a UUID stands for 'Universally Unique Identifier'. It is a standard code that includes a 128-bit identification number, which can be extended up to 36 characters.

It is commonly used to assign a unique identifier to information without requiring a central authority.

Syntax

Following is the syntax of the NodeJs crypto.randomUUID() method −

Crypto.randomUUID()

Parameters

  • This method does not accept any parameter.

Return value

This method returns a string containing a randomly generated, 36 character long v4 UUID.

Example 1

The following is the basic example of the NodeJs crypto.randomUUID() Method.

const { randomUUID } = require('crypto');  // crypto module
const uuid = randomUUID(); // randomUUID
console.log(uuid);

Output

The above program produces the following output −

856eb718-c0d0-481b-ae8a-2f4f600bce97

Example 2

When making API accessible, if you want to generate unique API access keys for the client, then you can use randomUUID().

const { randomUUID } = require('crypto');

function generateApiKey() {
    const apiKey = randomUUID();
    console.log(`Generate API key: ${apiKey}`);
    return apiKey;
}

const apiKey = generateApiKey();

Output

The above program produces the following output −

Generate API key: ff0858e4-a9c7-4074-bf69-8675b7a067b0

Example 3

In a web application you can use randomUUID() to create unique session identifiers(IDs) for the users when they login.

const { randomUUID } = require('crypto');
const sessionStore = {};

function createSession(userId) {
    const sessionId = randomUUID();
    sessionStore[sessionId] = { userId, createdAt: Date.now() };
    console.log(`Session created for user ${userId} with session ID: ${sessionId}`);
    return sessionId;
}

Output

After executing the above program it will display the following output −

Session created for user user123 with session ID: 2df24095-f982-48d4-81c5-e5abc36c2ab4
nodejs_crypto.htm
Advertisements