Open In App

How to generate unique ID with node.js?

Last Updated : 17 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how to generate a unique ID using Node.js. Unique ID means a string contains a unique identity throughout the program.

Table of Content

Prerequisites

Approach 1: Using UUID

UUID is a module of NPM (Node Package Manager). UUID stands for Universally Unique Identifier. It is used to create a highly unique idenitifier that should not be duplicated easily, and it contains 32 hexadecimal characters that are grouped into five segments, which are separated by a hyphen.

  • Install UUID
npm i uuid

Example : Implementation of above given UUID.

Javascript




// server.js
const uuid = require('uuid');
console.log('Unique ID:', uuid.v4());


Output:

Screenshot-2023-11-17-021355

Approach 2: Using Crypto

Crypto is a library of Node.js; you don’t need to install it separately in your project. It provides cryptographic functionality to Node JS.It can be used for the following requirements:

  • Hashing
  • Hash based message authentication code
  • Encryption and Decryption
  • Random Bytes

Example: Implementation of above approach.

Javascript




// Server.js
const crypto = require('crypto');
console.log('Unique ID:', crypto.randomBytes(16).toString('hex'));


Output:

Screenshot-2023-11-17-021852



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads