Pin a directory or file from IPFS to your Infura account using the kubo-rpc-client and nodejs

Hello everyone,

The kubo-rpc-client JavaScript library can be used to pin to your Infura IPFS account the CIDs of directories, together with the files they contain, which are uploaded to IPFS through other nodes or services than the Infura ones.
Take for example the CID of a test folder, like the one below, which is already uploaded to IPFS.

External Image

In order to pin it to your Infura account follow the next steps:
Install the library from the official kubo-rpc-client repository. Note that if you’ve previously used the ipfs-http-client to upload content to IPFS, it was deprecated and we recommend using the kubo client going forward.
Declare the IPFS client and use the below piece of code in order to pin the folder to your Infura IPFS account.
Don’t forget to use your Project ID and Project Secret.

Also keep in mind that the kubo client can only be imported as a module, so for simplicity save the below piece of code as an mjs file, index.mjs for example, before running it in node .

import { create } from 'kubo-rpc-client';
const projectId = '27h....xxx....Rsj';
const projectSecret = '205....xxx....d15b';

async function pinCid(){
    const auth =
      'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64')
    const client = await create({
        host: 'ipfs.infura.io',
        port: 5001,
        protocol: 'https',
        headers: {
          authorization: auth
        }
      })
      for await (const cid of client.pin.addAll('QmehKEbtk4wHihtfB48VF2WC6Sis3u1Ad2tbUsSUg5mmWH'))
     {
        console.log(cid)
      }
     }

pinCid()

Once you run the above code the CID will be displayed in the output window of your code runner:

External Image

Now you will find the CID of the pinned directory in the IPFS explorer of your Infura account.

External Image

While in your IPFS explorer, clicking the CID will display the objects the directory contains.

External Image

1 Like