Skip to content

window.crypto.randomUUID is undefined #47

@marcincodes

Description

@marcincodes

Expected Behavior

Fields should fallback to other solution when window.crypto.randomUUID() is not available

Current Behavior

window.crypto.randomUUID is undefined

Possible Solution

Write a fallback to react useId if it's available or getRandomValues() to generate uuid like id

function generateUUID() {
  // Check if crypto.randomUUID() is supported
  if (typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  } else if (typeof React !== "undefined" && typeof React.useId === "function") {
    // Fallback to React.useId, but keep in mind this might not generate a proper UUID
    const id = React.useId();
    return id; // Return the ID as-is since React.useId doesn't guarantee a UUID format
  } else {
    // Fallback to crypto.getRandomValues()
    // Generate an array of 16 random bytes
    const buffer = new Uint8Array(16);
    window.crypto.getRandomValues(buffer);

    // Convert the byte array to a hexadecimal string
    let uuid = '';
    for (let i = 0; i < buffer.length; i++) {
      uuid += ('00' + buffer[i].toString(16)).slice(-2); // Pad with zeros
    }

    // Replace dashes to mimic UUID v4 format
    uuid = uuid.replace(/-/g, '').replace(/\b(.{6})(.{4})(.{4})(.{12})\b/, '$1-$2-$3-$4');
    return uuid;
  }
}

Source: https://www.phind.com/search?cache=u11vgs2u05g6gdllheburzal

It will be even better to use useId from react and fallback to other solutions

Steps to Reproduce (for bugs)

  1. Use one of the browser that doesn't support randomUUID(). Here is a list: https://caniuse.com/?search=randomUUID

Context

crypto.randomUUID() is relatively new, it was introduced 3 years ago and projects that have users with <iOS 15.3 encounter this problem. Workaround for now is to patch collect-js-react package

Your Environment

  • Version used: 1.1.0
  • Browser Name and version: Safari < 15.4
  • Operating System and version (desktop or mobile): Mobile and Desktop
  • Link to your project:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions