I am trying to upload the metadata(JavaScript Object) of a file already uploaded to IPFS, from the client side in the NextJS. I am able to upload files(PDFs) to IPFS using the Infura's HTTP API
with the help of the ipfs-http-client
package, but I am not able to do so with JSON?
I have also tried uploading using the pinata SDK
but in vain.
How can I upload the JavaScript object to IPFS?
Asked
Active
Viewed 2,041 times
2

saditya
- 93
- 1
- 10
2 Answers
3
The Short Answer: Perform JSON.stringify()
on the JavaScript Object and upload the returned value to the IPFS. You can either use Infura's HTTP API end-point or ipfs-http-client
which is a client library for the IPFS HTTP API.
The Long Answer:
Uploading a file from user's disk:-
1. Using the ipfs-core
package:
- install the ipfs-core package
yarn add ipfs-core
- using ipfs-core package
import * as IPFS from 'ipfs-core'
const ipfs = await IPFS.create() //creating an IPFS node
//passing the file object extracted from the HTML input.
const { cid } = await ipfs.add(file)
console.info(cid) // QmXXY5ZxbtuYj6DnfApLiGstzPN7fvSyigrRee3hDWPCaf
2. Using a public IPFS gateway
- You can use this public IPFS gateway provided by Infura and use it to upload the files directly by sending a post request to this IPFS gateway.
- You can refer to this post on dev.to.
Uploading a JavaScript Object as a JSON:-
- You can upload a JavaScript Object to IPFS in the form of JSON text.
- First, you have to stringify the JSON using
JSON.stringify(<JS_OBJECT>)
and upload the returned value of this function to the IPFS. - You can use either of the two methods discussed above for uploading the value returned by this function.

saditya
- 93
- 1
- 10
0
You can use pinata-api without third party library
from the client you send the metadata to the server and the server sends post a request to pinata
.
const url = `https://api.pinata.cloud/pinning/pinJSONToIPFS`;
const res = await axios.post(
url,
{
pinataMetadata: {
name: "add a name",
},
// assuming client sends `nftMeta` json
pinataContent: req.body.nftMeta,
},
{
headers: {
pinata_api_key: yourPinataApiKey,
pinata_secret_api_key: yourPinataSecretApiKey,
},
}
);

Yilmaz
- 35,338
- 10
- 157
- 202
-
1The free pinata plan has limits to the number of IPFS uploads and fetches and stops working after the limit has reached. – saditya Nov 27 '22 at 09:38