Whether you need to generate a unique identifier for data key, object reference, url shortener, or duplication avoidance, a good random value generator library is a must-have. I recommend 4 libraries: uuid, short-uuid, nanoid, and crypto-random-string

This is not something you want to implement ad-hoc naively because there are serious number theory considerations were already put into these libraries to minimize collision probability thus enhance safety and more suitable for cryptography related use cases.

uuid is a straightforward way to generate standard RFC4122 UUIDs (128-bit Universally Unique Identifier)

const { v4: uuidv4 } = require('uuid')
uuidv4() // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

short-uuid serves similar purpose like above but allows converting back and forth between UUID and a shorter format for storage efficiency.

const short = require('short-uuid')

// Generate a shortened v4 UUID
const shortId = translator.new() //=>  mhvXdrZT4jP5T8vBxuvm75
 
// Translate UUIDs to and from the shortened format
const regularUUID = translator.toUUID(shortId); 
// a44521d0-0fb8-4ade-8002-3385545c3318
translator.fromUUID(regularUUID) // => mhvXdrZT4jP5T8vBxuvm75

nanoid is another alternative to UUID that has similar mathematical properties but designed to be faster and more compact by using a larger alphabet than UUID therefore less characters needed, whereby the size and alphabet are customizable. Moreover, there is also an async API that allows collecting more entropy by acquiring CPU noise in the background.

const nanoid = require('nanoid').nanoid

nanoid() //=> V1StGXR8_Z5jdHi6B-myT
// custom size, trade off between less storage and more collision probability
nanoid(10) //=> IRFa-VaY2b

crypto-random-string is a utility that generates random string with flexible customization. It worries less about collision probability, so it’s best suit where UUID is not needed and you care more about output representation.

const cryptoRandomString = require('crypto-random-string');
 
cryptoRandomString({length: 10});
//=> '2cf05d94db'
 
cryptoRandomString({length: 10, type: 'base64'});
//=> 'YMiMbaQl6I'
 
cryptoRandomString({length: 10, type: 'url-safe'});
//=> 'YN-tqc8pOw'
 
cryptoRandomString({length: 10, type: 'numeric'});
//=> '8314659141'
 
cryptoRandomString({length: 6, type: 'distinguishable'});
//=> 'CDEHKM'
 
cryptoRandomString({length: 10, type: 'ascii-printable'});
//=> '`#Rt8$IK>B'
 
cryptoRandomString({length: 10, type: 'alphanumeric'});
//=> 'DMuKL8YtE7'
 
cryptoRandomString({length: 10, characters: 'abc'});
//=> 'abaaccabac'

Bonus: Although I said you should you a robust library to generate random string instead of rolling your own, in case you don’t wish to include an external library and performance/probability is not a concern. This simple function will suffice:

function getNonce() {
	let text = '';
	const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	for (let i = 0; i < 32; i++) {
		text += possible.charAt(Math.floor(Math.random() * possible.length));
	}
	return text;
}

getNonce() // => mCuElQ2Qtmj68VlEosmOEcQkOpAKPG9M
Share This