Try   HackMD

How to Setup IPFS API for a Javascript Client

IPFS (the InterPlanetary File System) is a new hypermedia distribution protocol, addressed by content and identities.

IPFS is a system that aims to store data across a distributed network. I think this is the right direction for the modern web to move in. Unfortunately the current JS client implementation, ipfs-api, is a bit of a pain to setup. In this guide I'll walk you through the steps I took to get the library working with webpack.

Add the library and its dependencies

npm install --save ipfs-api
npm install --save-dev brfs

brfs acts as a shim to the fs module that's normally a part of node on the server side.

To use brfs we need to add the webpack transform loader.

npm install --save-dev transform-loader

Note for yarn users: You'll need to use the --ignore-engines flag to install brfs.

Edit your webpack config

To ensure that ipfs-api and its dependencies compile correctly we'll need to run them through brfs.

// webpack.config.js
module: {
  postLoaders: [
      {
        include: [
          path.resolve(__dirname, 'node_modules/ipfs-api'),
          path.resolve(__dirname, 'node_modules/fs.realpath'),
          path.resolve(__dirname, 'node_modules/libp2p-crypto'),
          path.resolve(__dirname, 'node_modules/ipld-dag-pb'),
        ],
        loader: 'transform/cacheable?brfs',
      },
  ]
}

At this point you'll probably receive the following error:

This is an issue with how the node-forge maintainers configured their builds. A workaround is to manually compile this library and add it to your repository.

npm install node-forge
cd node_modules/node-forge
npm install
run node node_modules/requirejs/bin/r.js -o minify.js optimize=none out=js/forge.bundle.js

Credit to @adamshone on forge issue #198

The next step is to copy the built forge.bundle.js into your project folder.

In this example we're going to copy it to src/utils/forge.bundle.js.

Add the compiled forge bundle to your build

Now we need to alias node-forge to use the built bundle instead of the folder in node-modules.

// webpack.config.js
resolve: {
  alias: {
    'node-forge': path.resolve(__dirname, 'src/utils/forge.bundle.js')
  }
}

If you're receiving this error, you're on the right track:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

This is because webpack is processing the already built forge bundle. The bundle needs to be excluded from any loaders that might be processing it. Here's an excerpt from my webpack config:

module: {
  loaders: {
    {
      test: [/\.js$/, /\.jsx$/],
      loaders: ['babel'],
      exclude: /(node_modules|forge\.bundle\.js)/,
    }
  }
}

Congratulations, you can now use IPFS on your JS client app.

References