How to generate UUID (unique id) without any library.

We can always use libraries like nanoid.

But have you ever wondered, how you can generate the random string ids for your code?

Here's the trick.

Using crypto 

The Crypto interface represents basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives.

It is built-in javascript framework, so you don't need to worry about adding external library to your code.

Instance methods
This interface implements methods defined on RandomSource.

 crypto.getRandomValues() 
Fills the passed TypedArray with cryptographically sound random values.

const array = [1,2,3,4,5,6,7]
window.crypto.getRandomValues(array);

// result -> 6

 

 crypto.randomUUID()  
Returns a randomly generated, 36-character long v4 UUID.

window.crypto.randomUUID()
// result -> '79304ea7-a799-43d9-b8c9-6fc725537570'

source: MDN

 

Using your self-created method

function generateUUID() {
    let d = new Date().getTime();
    let d2 = (performance && performance.now && (performance.now()*1000)) || 0;

    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        let r = Math.random() * 16;
        if(d > 0){
            r = (d + r)%16 | 0;
            d = Math.floor(d/16);
        } else {
            r = (d2 + r)%16 | 0;
            d2 = Math.floor(d2/16);
        }
        return (c==='x' ? r : (r&0x3|0x8)).toString(16);
    });
}

console.log(generateUUID());

This function generates a version 4 UUID, which is randomly generated. The UUID format is xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where the 4 indicates the UUID version and y is one of 8, 9, A, or B.