Skip to content

OrbitDB on React Native - IndexedDB Issue with Keystore #1217

Closed

Description

@palmtown

Hello everyone,

I’m working on integrating OrbitDB into a React Native project and have encountered an issue. libp2p and Helia are both functioning correctly.
However, when I run:

await createOrbitDB({ ipfs })

I get the following error:

ReferenceError: Property 'indexedDB' doesn't exist.

It seems that this issue is related to the Keystore, as IndexedDB is not available in React Native.

Questions:

  1. Has anyone successfully used a different Keystore in React Native?
  2. Does anyone have working code for using OrbitDB in a React Native project?

This is currently blocking my progress, and I’d appreciate any insights. Thanks in advance!

Activity

  1. haydenyoung commented on Feb 11, 2025

    @haydenyoung
    Member

    Okay so I don't really have any experience with React Native outside of testing it out maybe a few years ago, but I can suggest something regarding OrbitDB.

    Firstly, is there any stack trace regarding the error ReferenceError: Property 'indexedDB' doesn't exist.? If so, I'm going to guess that the error is originating from LevelDB. If this is the case, I'm wondering if there is a different level implementation for React Native.

    The approach would then be:

    1. Create a custom storage. Could be based on this.
    2. Explicitly create a KeyStore and pass it the custom storage.
    3. Create identities using keystore and pass to createOrbitDB and orbitdb.open.

    If nobody else has any suggestions as to a React Native implementation I would be happy to help you where I can to implement your requirement.

  2. palmtown commented on Feb 11, 2025

    @palmtown
    Author

    Hello @haydenyoung

    Thank you for your update. Before reading your post, I implemented a custom KeyStore to bypass the ReferenceError: Property 'indexedDB' doesn't exist issue, which allowed the await createOrbitDB({ipfs, identities}) function to run successfully. However, I then encountered an error in the database open function:

    TypeError: _options$signal.throwIfAborted is not a function (it is undefined)

    This error is triggered by the following line in the code await ipfs.blockstore.put(cid, data, {signal}); at
    GitHub link

    Based on your recommendation, I now realize that I should have created a custom storage instead of a custom KeyStore. I will try that approach and keep you posted on the results.

    Thank you again.

  3. palmtown commented on Feb 11, 2025

    @palmtown
    Author

    Hello @haydenyoung

    Based on your recommendation, I created a custom storage provider (see Exhibit 1 below), but encountered the following issues:

    1. I ran into the same error as before:
      TypeError: _options$signal.throwIfAborted is not a function (it is undefined).
      After debugging, I found that { signal } in await ipfs.blockstore.put(cid, data, { signal }); was the cause. Removing it for testing allowed me to proceed.

    2. Regarding your third recommendation:
      "Create identities using keystore and pass them to createOrbitDB and orbitdb.open."
      I passed identities to orbitdb.open, but encountered another error in createOrbitDB:
      ReferenceError: Property 'indexedDB' doesn't exist.

    My research pointed to issues with headsStorage and indexStorage. While entryStorage might also be problematic, it did not throw an error when calling orbitdb.open.

    Passing my custom storage provider to headsStorage, indexStorage, and entryStorage resolved this issue, allowing orbitdb.open to execute successfully.

    1. When executing orbitdb.put to add a document, I encountered:
      CBOR decode error: data to decode must be a Uint8Array.

    Implementing a different custom storage with Uint8Array support helped, but led to additional CBOR decode errors, suggesting my storage solution may be inadequate.

    Any guidance on resolving these issues would be greatly appreciated!

    Thanks!

    Exhibit 1 - Custom Storage

    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    export interface AsyncStorageProviderOptions {
      prefix?: string;
    }
    
    /**
     * Creates an instance of AsyncStorageProvider.
     * @param {AsyncStorageProviderOptions} [options={}] Optional configuration.
     * @return An object with storage methods.
     */
    const AsyncStorageProvider = ({
      prefix = '',
    }: AsyncStorageProviderOptions = {}) => {
      const buildKey = (key: string) => `${prefix}${key}`;
    
      const put = async (key: string, value: any): Promise<void> => {
        const storedValue =
          typeof value === 'string' ? value : JSON.stringify(value);
        await AsyncStorage.setItem(buildKey(key), storedValue);
      };
    
      const get = async (key: string): Promise<any | undefined> => {
        const storedValue = await AsyncStorage.getItem(buildKey(key));
        if (storedValue === null) return undefined;
        try {
          return JSON.parse(storedValue);
        } catch {
          return storedValue;
        }
      };
    
      const del = async (key: string): Promise<void> => {
        await AsyncStorage.removeItem(buildKey(key));
      };
    
      const iterator = async function* ({
        amount,
        reverse,
      }: {amount?: number; reverse?: boolean} = {}): AsyncGenerator<
        [string, any],
        void,
        unknown
      > {
        let keys = await AsyncStorage.getAllKeys();
    
        if (prefix) {
          keys = keys.filter(key => key.startsWith(prefix));
        }
        if (reverse) keys = keys.slice().reverse();
        if (amount !== undefined && amount >= 0) {
          keys = keys.slice(0, amount);
        }
        if (!keys.length) return;
    
        const keyValues = await AsyncStorage.multiGet(keys);
        for (const [key, value] of keyValues) {
          const originalKey = prefix ? key.substring(prefix.length) : key;
          let parsedValue: any = value;
          if (value !== null) {
            try {
              parsedValue = JSON.parse(value);
            } catch {
              // value remains as string if JSON.parse fails.
            }
          }
          yield [originalKey, parsedValue];
        }
      };
    
      const merge = async (other: {[key: string]: any}): Promise<void> => {
        await Promise.all(
          Object.entries(other).map(([key, value]) => put(key, value)),
        );
      };
    
      const clear = async (): Promise<void> => {
        if (prefix) {
          let keys = await AsyncStorage.getAllKeys();
          keys = keys.filter(key => key.startsWith(prefix));
          await AsyncStorage.multiRemove(keys);
        } else {
          await AsyncStorage.clear();
        }
      };
    
      const close = async (): Promise<void> => {
        // AsyncStorage doesn't require an explicit close.
        return;
      };
    
      return {put, del, get, iterator, merge, clear, close};
    };
    
    export default AsyncStorageProvider;
    
  4. haydenyoung commented on Feb 13, 2025

    @haydenyoung
    Member

    So there may be a couple of issues going on but we should probably focus on the first, which is the incompatibility of Level with React Native.

    In the first instance, are you able to create a basic example and try the following:

    1. Reproduce the indexedDB problem with Level. IF we can, we isolate the problem to LevelDB.

    2. Try a Level implementation for React Native, swapping out the standard library for something more React Native-friendly.

    Once we have a robustness Level-based data store, we can introduce this to OrbitDB.

    All issues are pointing to issues with out-of-the-box level. headsStorage and indexStorage definitely use Level. Identities I can't remember I'd have to take a look.

    Let's address the CBOR issue after establishing a stable Level implementation.

  5. palmtown commented on Feb 14, 2025

    @palmtown
    Author

    Hello @haydenyoung

    Thank you for you response. Please note that I was able to resolve the issue TypeError: _options$signal.throwIfAborted is not a function (it is undefined). with the below code in Exhibit 1. Now it doesn't throw that error. Secondly, the problem is LevelDB. Simply put, React Native doesn't provide the built-in bindings for LevelDB.

    However, there is a package, https://www.npmjs.com/package/react-native-leveldb that could be leveraged. Any help you may be able to provide to get this implemented would be great.

    Exhibit 1

    global.AbortSignal.prototype.throwIfAborted = function () {
      if (this.aborted) {
        throw new Error('Aborted');
      }
    };
    
  6. haydenyoung commented on Feb 14, 2025

    @haydenyoung
    Member

    My thinking is to start with a React Native solution to the LevelDB problem. I had a quick look at react-native-leveldb and it would probably be a good idea to implement something stand-alone. If you can set up a leveldb then put and get a record in React Native, this could for the basis of a custom storage for React Native-specific OrbitDB instances.

    If you are on Matrix, please feel free to reach out to me directly. It may be easier to solve this in real time. https://matrix.to/#/#orbitdb_Lobby:gitter.im

  7. haydenyoung commented on Mar 2, 2025

    @haydenyoung
    Member

    @palmtown were you able to make any progress on this?

  8. palmtown commented on Mar 3, 2025

    @palmtown
    Author

    Hello @haydenyoung

    Thanks for following up. Please note that yes, I was able to make progress. In short, react-native-leveldb will solve this issue. However, I come to find an integration issue between libp2p and react-native using react-native-tcp-sockets. Specifically, TCP is not working due to a few issues. Therefore, I am working on this issue for now.

    Once this is resolved, I will circle back around. Feel free to close this issue if you'd like, I can always re-open once I've resolve the TCP issue.

  9. haydenyoung commented on Mar 3, 2025

    @haydenyoung
    Member

    @palmtown Thanks for the update and good to hear you are having success. It may be worth opening up this discussion on libp2p as someone may have experienced a similar issue. Also, the libp2p developers may be aware of these issues (I believe there is some integration of react native in both libp2p and helia).

    I would recommend asking around on the Libp2p Slack channel as a start. If you post your question here, I will follow up to let the Libp2p developers know we are actively working on this solution.

  10. haydenyoung commented on Aug 4, 2025

    @haydenyoung
    Member

    I'm going to close this issue as there hasn't been any updates from the OP. If any new information is forthcoming, please reopen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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