discogs-client icon indicating copy to clipboard operation
discogs-client copied to clipboard

Getting "Cannot read property 'randomUUID' of undefined" when using outside the browser environment

Open 404-html opened this issue 1 year ago • 2 comments
trafficstars

I tried to use DiscogsOAuth in React Native app and following was thrown:

TypeError: Cannot read property 'randomUUID' of undefined

I believe this is because the library is trying to access window, which is specific for browser environment: https://github.com/lionralfs/discogs-client/blob/77a139c3b3f025316c942f5c7ea97157f7bc75e3/browser/crypto.js#L5

So the question is if...

discogs-client is a Node.js and browser client library

I believe that's the only problematic place, and using something different instead should fix the problem. Here's an example implementation:

function randomUUID(): string {
  // Create an array of 16 random bytes (128 bits)
  const randomBytes = new Uint8Array(16);
  crypto.getRandomValues(randomBytes);

  // Set the version to 4 (UUIDv4) and the variant to 10x (as per the UUID v4 specification)
  randomBytes[6] = (randomBytes[6] & 0x0f) | 0x40; // Set version to 4
  randomBytes[8] = (randomBytes[8] & 0x3f) | 0x80; // Set variant to 10x

  // Convert the byte array to a UUID string in the format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  const uuid = [...randomBytes]
    .map((byte, index) => {
      // Add dashes in the specific UUID positions
      const hex = byte.toString(16).padStart(2, '0');
      return [4, 6, 8, 10].includes(index) ? `-${hex}` : hex;
    })
    .join('');

  return uuid;
}

404-html avatar Oct 19 '24 09:10 404-html

Hey, how does your import look like? Do you have something like this:

import { DiscogsClient } from '@lionralfs/discogs-client/browser';

And does it change anything if you change it to this:

import { DiscogsClient } from '@lionralfs/discogs-client';

In theory, only the browser-specific bundle loads the function that accesses window.crypto

lionralfs avatar Oct 21 '24 15:10 lionralfs

Thank you for the reply @lionralfs. My import looks as follows:

import { DiscogsClient } from '@lionralfs/discogs-client';

Looks like using when the library in React Native project it falls back to browser bundle. I tested that by removing browser directory from node_modules. After that I was getting import errors, because the imported file was not found.

I also dug a but more, and I am afraid that a bit more work is required to make this library React Native friendly:

So this issue might led to a bigger task, which is making discogs-client React Native friendly. If you would like to proceed - I am happy to help.

404-html avatar Oct 26 '24 09:10 404-html