Search code examples
ipfs

How to start IPFS in browser by using only DHT WebRTC peers?


I'm using this code in the browser. It seems to be connecting to ipfs.io via http?. I'm looking to only connect to DHT webRTC peers. I'm guessing I need to pass some option to Ipfs.create? I see an example of custom libp2p here but the amount of options are overwhelming. https://github.com/ipfs/js-ipfs/blob/master/examples/custom-libp2p/index.js

<script src="https://cdn.jsdelivr.net/npm/ipfs/dist/index.min.js"></script>
<script>
    (async () => {
        const node = await Ipfs.create()

        const data = 'Hello'
        const results = await node.add(data)
        console.log(results)
    })()
</script>

Solution

  • You can pass the IPFS config options when creating the instance, which enables you to specify the remote WebRTC addresses you want to listen on, and remove/change the Bootstrap nodes to initially connect to. You can see this in the file exchange example at https://github.com/ipfs/js-ipfs/blob/ipfs%400.49.1/examples/browser-exchange-files/public/app.js#L48. So your config might look like this:

    const node = await Ipfs.create({
      config: {
        Addresses: {
          Swarm: [
            // These are public webrtc-star servers
            '/dns4/wrtc-star1.par.dwebops.pub/tcp/443/wss/p2p-webrtc-star',
            '/dns4/wrtc-star2.sjc.dwebops.pub/tcp/443/wss/p2p-webrtc-star'
          ]
        },
        // This removes the default IPFS peers to dial to. You can specify any known addresses you wish, or leave blank.
        Bootstrap: []
      }
    })
    

    As you've mentioned the DHT I just want to note that running a DHT over WebRTC is really not viable outside of a small, isolated network. As WebRTC dialing can take some time, this has a huge impact on DHT query times.