How to upload files on IPFS infura.io using React

Hello :wave: all! Today we’re going to develop a simple React App using ipfs-http-client to upload data using our Infura Dedicated gateway.

Things we are going to do.

  • We will create and setup our Infura account
  • We will develop a simple React app to upload files on IPFS
  • We access the uploaded content from IPFS using our Infura Dedicated Gateway

Setting up the infura account.

Go to the official website infura.io and create a new account. After creating it click on the create new key as seen in the screenshot below.


Prerequisites: Use your own Project ID and Project Secret.

After creating the IPFS project, you’ll have to set up your dedicated gateway name (Subdomain must only contain letters, numbers, and dashes)

Creating our React app

Our first step is installing the ipfs-http-client in our React app using npm. Install it using the below command:

npm install ipfs-http-client@50.1.2

Note: If you are installing the latest version of ipfs-http-client (57.0.3) with just npm install ipfs-http-client
There are some slight changes on how it is imported referenced here: ipfs-http-client - npm

In our App.js file we have to import { create } from ‘ipfs-http-client’ and set up our Infura credentials (PROJECT ID + API KEY SECRET)

import { create } from 'ipfs-http-client'

const projectId = '...';
const projectSecret = '...';
const auth = 'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const client = create({
  host: 'ipfs.infura.io',
  port: 5001,
  protocol: 'https',
  apiPath: '/api/v0',
  headers: {
    authorization: auth,
  }
})

We will create a variable client which stores the ipfs http client return by the create function. We will pass the url and the headers including authorization. (If we don’t include the above authorization, our app will throw an invalid project id error)

In our app we will create a async function onChange (e) which will use our dedicated gateway URL and upload the files using a simple HTML button.

async function onChange(e) {
    const file = e.target.files[0]
    try {
      const added = await client.add(file)
      const url = `https://yourdedicatedgwname.infura-ipfs.io/ipfs/${added.path}`
      updateFileUrl(url)
    } catch (error) {
      console.log('Error uploading file: ', error)
    }  
  }
  return (
    <div className="App">
      <h1>IPFS Example</h1>
      
      <input
        type="file"
        onChange={onChange}
      />
      {
        
        fileUrl && (
          <img src={fileUrl} width="600px" /> 
        )
      }
      <p>{fileUrl}</p>

We will display the image we’re uploading and add the URL to our view so we’re able to access the newly created CID from our dedicated gateway.

We have completed all the steps for uploading files from a simple React App. You may want to check out the full code repository here → Ipfs-http-client example.

2 Likes