Tiny react hook to upload files into IPFS

For hellocurator we want to let users upload an image through our application. The solution of choice for decentralized storing is IPFS.

IPFS is a distributed system for storing and accessing files, websites, applications, and data. I recommend reading the doc if you want to know more about the concepts.

Since our app is written in Next.js, we will use React with a custom hook. But you can take the functionality with any other JavaScript framework.

The code

We will use the ipfs-http-client library.

npm i ipfs-http-client

import { create } from "ipfs-http-client";
import { ImportCandidate } from "ipfs-core-types/src/utils";
const client = create({ url: "https://ipfs.infura.io:5001/api/v0" });
const useIpfs = () => {
const upload = async (file: ImportCandidate) => {
try {
const added = await client.add(file);
const url = `https://ipfs.infura.io/ipfs/${added.path}`;
return url;
} catch (error) {
console.error("Error uploading file: ", error);
return {
export default useIpfs;

The basic functionality takes 3 lines of code:

  • create a client with a gateway. There are different types of gateway for IFPS. For our example, we use a free one by infura.io, but you can use other services or create your own.
  • Import a file or data into IPFS
  • Get the path of the stored file

You can use this hook for storing anything you want on IPFS.

const onSubmit: SubmitHandler<FormValues> = async (data) => {
const image = data.image[0];
/* upload an image */
const imageUrl = await upload(image);
/* upload a file */
const fileUrl = await upload(data.file);
/* upload a text */
const textUrl = await upload("hello!");
/* upload a JSON */
const jsonUrl = await upload(
title: "hellocurator",
description: "We’re happy to introduce hellocurator",
/* etc. */

GitHub Gist

Published: 3/17/2022

Join my newsletter to stay updated about the latest things I've created and discover the great finds I've come across on the internet.