How to Generate UUID in Node.js Using uuid Package
To generate a UUID in
Node.js, install the uuid package and use its v4() function for random UUIDs. Import it with import { v4 as uuidv4 } from 'uuid' and call uuidv4() to get a unique identifier string.Syntax
Use the uuid package's v4() function to generate a random UUID. First, import the function, then call it to get a unique string.
import { v4 as uuidv4 } from 'uuid': imports the UUID version 4 generator.uuidv4(): generates a new random UUID string.
javascript
import { v4 as uuidv4 } from 'uuid'; const id = uuidv4(); console.log(id);
Output
a string like '3a017f3e-8f9b-4c6a-9f3d-2a1b4e5c6d7f'
Example
This example shows how to generate and print a UUID in Node.js using the uuid package. It demonstrates the import, generation, and output of a unique identifier.
javascript
import { v4 as uuidv4 } from 'uuid'; function generateUUID() { const newUUID = uuidv4(); console.log('Generated UUID:', newUUID); } generateUUID();
Output
Generated UUID: 9b1deb4d-3b7d-4f7a-9f3e-2a1b4e5c6d7f
Common Pitfalls
Common mistakes include not installing the uuid package, using deprecated methods, or importing incorrectly.
- Forgetting to run
npm install uuidbefore using it. - Using the old
require('uuid/v4')syntax which is deprecated. - Not using ES module import syntax in modern Node.js setups.
javascript
/* Wrong way (deprecated or incorrect) */ // const { v4: uuidv4 } = require('uuid'); // Deprecated way to require v4 directly /* Right way */ import { v4 as uuidv4 } from 'uuid'; const id = uuidv4(); console.log(id);
Quick Reference
Summary tips for generating UUIDs in Node.js:
- Always install the
uuidpackage withnpm install uuid. - Use ES module import:
import { v4 as uuidv4 } from 'uuid'. - Call
uuidv4()to get a new UUID string. - UUIDs are useful for unique IDs in databases, sessions, or identifiers.
Key Takeaways
Install the uuid package before using it in Node.js projects.
Use ES module syntax: import { v4 as uuidv4 } from 'uuid'.
Call uuidv4() to generate a random UUID string.
Avoid deprecated import styles like require('uuid/v4').
UUIDs provide unique identifiers useful for many applications.