Skip to content

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

Open
@404-html

Description

@404-html

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:

return window.crypto.randomUUID().slice(0, 64);

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions