How to Generate Unique ID in JavaScript
To generate unique ID's in JavaScript, use the uuid
NPM package. This is a nice solution as the package has a tiny footprint and allows you to generate RFC4122 version 1, 3, 4, and 5 cryptographically-strong random UUIDs anywhere in your program.
Install the uuid NPM Package
In the root of your project (or where NPM is accessible) run the following command to install the uuid
package:
npm i uuid
Add uuid to JS File and Use it
At the top of your JS file, require()
the uuid
package and store it in a constant. In my case, I am only using UUID version 4 so I only need to require uuid/v4
:
const uuidv4 = require("uuid/v4")
Now you can generate unique ID's like this:
var id = uuidv4();
e194db56-5bdd-44f8-9f44-36ecd9d00f6e