Cannot read property ‘digest’ of undefined in ReactNative

Hello, I have faced a problem same as this Cannot read property ‘digest’ of undefined
Of cause, I tried to solve it, but I couldn’t.

Background
I used "@web3auth/react-native-sdk": "^3.5.0", but they stopped support.
so I tryed to update.

async function sha512(msg: Buffer): Promise<Uint8Array> {
  if (!browserCrypto.createHash) {
    const hash = await subtle.digest("SHA-512", msg); <- subtle is undefined
    const result = new Uint8Array(hash);
    return result;
  }
  const hash = browserCrypto.createHash("sha512");
  const result = hash.update(msg).digest();
  return new Uint8Array(result);
}

Also

const browserCrypto = globalThis.crypto || globalThis.msCrypto || {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
subtle is undefined

Code Snipet is

import Web3Auth, {
  LANGUAGES,
  LOGIN_PROVIDER,
  WEB3AUTH_NETWORK,
} from '@web3auth/react-native-sdk';
import EncryptedStorage from "react-native-encrypted-storage";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import * as WebBrowser from '@toruslabs/react-native-web-browser';
import {
  CHAIN_NAMESPACES,
  IAdapter,
  IProvider,
  getEvmChainConfig,
} from '@web3auth/base';
import axios from 'axios';

  const network =
    Config.ENV === 'DEBUG' ? WEB3AUTH_NETWORK.TESTNET : WEB3AUTH_NETWORK.CYAN;

  const privateKeyProvider = new EthereumPrivateKeyProvider({
    config: {
      chainConfig: {
        chainNamespace: CHAIN_NAMESPACES.EIP155,
        chainId: "0x1",
        rpcTarget: "https://rpc.ethereum.org",
        displayName: "Ethereum Mainnet",
        blockExplorerUrl: "https://etherscan.io",
        ticker: "ETH",
        tickerName: "Ethereum",
      },
    },
});

  const whiteLabel = {
    name: 'NAME'
    logoLight: '',
    defaultLanguage: LANGUAGES.ja,
    theme: {
      primary: '#000000',
    },
  };

  const web3auth = new Web3Auth(WebBrowser, EncryptedStorage, {
    clientId: Config.WEB3AUTH_CLIENTID ?? '',
    network: network,
    whiteLabel: whiteLabel,
    privateKeyProvider,
    redirectUrl: '',
    loginConfig: {
      jwt: {
        verifier: 'apple-questry',
        typeOfLogin: 'jwt',
        clientId: Config.AUTH0_CLIENTID,
      },
    },
  });

export const init = async () => {
  await web3auth.init();
} 

export const handleLoginProviderClick = onClose => {
  const redirectUrl =
    Platform.OS === 'android'
      ? Config.REDIRECT_URL_ANDROID
      : Config.REDIRECT_URL_IOS;

  web3auth
    .login({
      // https://web3auth.io/docs/sdk/pnp/react-native/custom-authentication#using-auth0-login
      loginProvider: LOGIN_PROVIDER.JWT,
      redirectUrl,
      extraLoginOptions: {
        domain: Config.AUTH0_DOMAIN,
        verifierIdField: 'sub',
      },
    })
    .then(async result => {
      console.log("result", result)
      onClose();
      try {
        RNRestart.Restart();
      } catch (error) {
        console.log('Restart Error: ', error);
      }
    })
    .catch(error => {
      console.error('Error: ', error);
    });
};

same as documents in Web3Auth

Regards

Thank you for providing detailed information and code snippets—this is very helpful!

Summary for Support Team:

  • SDK: @web3auth/react-native-sdk
  • SDK Version: ^8.1.0 (recently updated from ^3.5.0)
  • Platform: React Native (iOS)
  • Issue: TypeError: Cannot read property ‘digest’ of undefined
    • Error trace points to subtle being undefined in the sha512 function (from the eccrypto dependency).
    • This occurs during the login process, specifically when encrypting data using metadataHelpers.encryptData.
  • Authentication: Custom JWT (Auth0) with verifier apple-questry
  • Code Snippet: Provided (initialization, login logic, and configuration)
  • Reference: Similar issue previously reported (community link)

What’s Happening

This error typically occurs because the underlying cryptography library (eccrypto) is trying to use the Web Crypto API (crypto.subtle), which is not natively available in React Native environments. The error is triggered during cryptographic operations (like sha512 hashing) when globalThis.crypto.subtle is undefined.

Proposed Solution

1. Install a Polyfill for crypto and subtle in React Native

React Native does not provide a built-in Web Crypto API. You need to polyfill it.
The recommended solution is to use react-native-quick-crypto, which provides a Node.js-compatible crypto implementation.

Steps:

  1. Install the package:

    yarn add react-native-quick-crypto
    
  2. Add the polyfill at the top of your entry file (e.g., index.js):

    import 'react-native-quick-crypto';
    global.crypto = require('crypto');
    
  3. Rebuild your app:

    • For iOS:
      cd ios && pod install && cd ..
      yarn react-native run-ios
      
    • For Android:
      yarn react-native run-android
      

References:


Next Steps:

  • Please try adding the crypto polyfill as described above.
  • If the issue persists, let us know if you see any new errors, and please share any relevant logs or screenshots.

Let me know if you need further guidance or if the polyfill resolves your issue!

Note: This response was generated by an AI bot and may require further verification. The Web3Auth support team has tracked this issue and will be responding as soon as possible.

Additionally, we would recommend you to join our biweekly Office Hours to get this resolved even faster. Web3Auth Developer Office Hours