IPFS and Angular 6

Get Started with the InterPlanetary File System

GrandSchtroumpf
2 min readOct 15, 2018

The code of the project can be found in this repo.

What is IPFS ?

According to the Github, IPFS is “ A peer-to-peer hypermedia protocol”. This is a decentralized and versioned File System that aims to replace HTTP. I like to see it as a mix between Git and Torrent. You can use it to host your static website, or as a decentralized storage.

Let’s see how to use it with Angular.

Installing and config

IPFS comes with a Javascript version that works with Nodejs and on the Browser. Let’s install it :

npm install ipfs async --save

Note: I install async because ipfs needs it as a dependency, but doesn’t install it by itself.

Custom Webpack Builder

Like most cryptographic-based library, you’ll need to append the angular’s default webpack config to allow node modules.

For more details see this article.

  1. Start by installing the builders:
npm install --save-dev  @angular-builders/custom-webpack  @angular-builders/dev-server

2. Then, in angular.json change :

  • The builder of build with @angular-builders/custom-webpack:browser
  • The builder of serve with @angular-builders/dev-server:generic

3. Finally, create a webpack.config.js file at the root of the project :

The needed webpack config for IPFS

The IPFS Service

Let’s build a simple InjectionToken around the IPFS constructor to leverage the power of Angular dependency injection :

Create a ipfs.ts file inside src/app :

An Injection Token around the ipfs constructor

Now you can use it in your app.component.ts :

In this example we wait for the ipfs node to be ready, then we :

  • Log the version of the node.
  • Write a hello.txt file in the node.
  • Read the hello.txt file based on its hash.

This is ok, but waiting for the ipfs node to be ready is kind of annoying. Let’s see how to work around that.

APP INITIALIZER

Angular comes with this handy injection token call APP_INITIALIZER that is loaded before the app. It can trigger a factory that does some async calls before the app is bootstrapped. The is very convenient for config initialization, like our ipfs.on('ready') event.

The factory

In ipfs.ts add the factory initIPFS :

Note: The factory is a function that returns a function that returns a Promise.

The Initializer

Now add the APP_INITIALIZER token, using this factory, in your app.module.ts :

We pass the IPFS token as a deps which is the node argument in the initIPFS factory just above.

Use it in the component

In your app.component.ts

Here we don’t need to wait for the ipfs node to be ready, which makes it more convenient to use in your code.

You can find the result of the project in this repo.

--

--

GrandSchtroumpf

I co-founded DappsNation, a Blockchain studio that build awesome decentralized applications. I also work at the Ethereum Foundation for the Remix project.