Search code examples
javascriptreactjsuuid

Generating UUID in react using crypto api


According to MDM (https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID) Most modern Browsers support the javascript native crypto api, which supports the former node-js crypto standard.

According to this article in plain js I may create an uuid via

crypto.randomUUID()

Is there any way to use this interface in react? Since crypto seems to refere to a completely different object in react.

ps. I am aware of the existence of the UUID package, and know that its a common way to generate UUIDs I am just curious.


Solution

  • I guess you are right, the crypto package in React is a different one. To use the one from NodeJs you can call:

    window.crypto

    I put it in the if to make sure, it is only rendered in the browser.

    if (window !== undefined) {
        console.log('randomUUID', window.crypto.randomUUID());
    }
    

    or

    import crypto from 'crypto';
    
    console.log('crypto.randomUUID()', crypto.randomBytes(16).toString('hex'));