Generate a unique ID string in Node.js?

Answered
nick asked this question 1 year, 5 months ago
nick on Jan 4, 2022

What is the best way to generate a unique ID using Node.js? It should be in the form of a string.

I'm open to using pure JavaScript and/or an external NPM package.

Thanks in advance!

3 suggested answers
yaboy01 on Jan 12, 2022

If you don't mind using a NPM package, nanoid is a great tool.

Install it like this:

npm install --save nanoid

And it can be put to use like this:

const nanoid = require("nanoid")

const generateUniqueId = function(length) {
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

  const generator = nanoid.customAlphabet(alphabet, length)

  return generator()
}

This function takes a given length and returns a random ID string with that given length. The alphabet contains the numbers and letters to include in the ID. Change that to whatever you want in yours.

You'd use the function like this:

generateUniqueId(12) // returns "pvSCCiqx0WsD"

You can test the probability of creating duplicate IDs here: https://zelark.github.io/nano-id-cc/.

0 replies
looper003 on Jan 12, 2022

uuid is a very popular and widely tested NPM package you can use:

const {v4: uuidv4} = require("uuid")

uuidv4() // "e6ba3ab5-43f4-4ff9-98db-576ba1833e06"

This creates a RFC4122 UUID.

0 replies
itsbambi on Jan 12, 2022
function guidGenerator() {
    var S4 = function() {
       return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }

    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4())
}

This function returns a UUID in a 5f924b45-06ba-0e65-7407-853005e2d539 format.

0 replies
Answered