js-libp2p: `TypeError: TextDecoder is not a constructor` when handling multiaddresses in browser

  • Version: libp2p 0.30.12
  • Platform:
    • Firefox 87.0
    • Chrome `89.0.4389.114’
    • Platform: Darwin Kernel Version 20.3.0: Thu Jan 21 00:07:06 PST 2021; root:xnu-7195.81.3~1/RELEASE_X86_64 x86_64 macOs Big Sur 11.2.3
  • Subsystem:

Type:

Bug

Severity:

Critical

Description:

When handling any kind of code that depends on https://github.com/multiformats/js-multibase the application crashes in the Browser with:

TypeError: TextDecoder is not a constructor
./node_modules/multiaddr/node_modules/multibase/src/util.js
node_modules/multiaddr/node_modules/multibase/src/util.js:6

  3 | // @ts-ignore
  4 | const { TextEncoder, TextDecoder } = require('web-encoding')
  5 | 
> 6 | const textDecoder = new TextDecoder()
  7 | /**
  8 |  * @param {ArrayBufferView|ArrayBuffer} bytes
  9 |  * @returns {string}

Test with Firefox and Chrome.

Using require for importing resulted in the same error. Using multiaddr function like shown in the chat example https://github.com/libp2p/js-libp2p/blob/master/examples/chat/src/dialer.js#L33 resulted in the same error.

The problem seems to be related to how imports are handled in multibase.

Steps to reproduce the error:

I ran into this problem when building a PoC trying to connect to a rust-libp2p daemon with js-libp2p from the browser: https://github.com/da-kami/js-libp2p-quote-poc

Note: I also did a pure Javascript version which failed with the same error.

Are we missing something for working with Mutiaddress in the browser or is this a bug?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 2
  • Comments: 25 (22 by maintainers)

Most upvoted comments

Ok I can confirm the error is gone with rc.3 😃

Yes, facing an issue too when trying the release candidate:

../node_modules/libp2p/src/upgrader.js 315:14
Module parse failed: Cannot use keyword 'await' outside an async function (315:14)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|             stream,
|             protocol
>           } = await mss.select(protocols);
|           if (this.metrics) this.metrics.trackStream({
|             stream,

As a temporary quickfix we use yarn’s resolutions feature to upgrade multibase and uint8arrays to the latest version which removes web-encoding:

https://github.com/da-kami/js-libp2p-quote-poc/blob/master/package.json#L23-L26