How to generate unique ID with node.js?
Last Updated :
24 Apr, 2025
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.
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.
npm i uuid
Example : Implementation of above given UUID.
JavaScript
// server.js
const uuid = require('uuid');
console.log('Unique ID:', uuid.v4());
Output:

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'));