Having trouble uploading the file to IPFS: Encounter an issue with HTTPError: project id is mandatory

Currently in the process of developing a basic DApp for sharing chats, with similarities to Twitter but based on a smart contract. I am utilizing hardhat and running my application on localhost. While implementing the feature for users to upload a profile picture when creating their profiles, I encountered an issue:

POST https://ipfs.infura.io:5001/api/v0/add?stream-channels=true&progress=false 401 (Unauthorized)

This error message appeared along with the above error:

Error uploading file: HTTPError: project id required

    at Object.errorHandler [as handleError] (core.js?edc8:103:1)
    at async Client.fetch (http.js?8f3e:149:1)
    at async addAll (add-all.js?93f2:36:1)
    at async last (index.js?7e49:13:1)
    at async Object.add (add.js?6672:22:1)

The console indicates that the error is arising from this function:

    const uploadToInfura = async (file) => {
      try {
        const added = await client.add({ content: file });
  
        const url = `https://ipfs.infura.io/ipfs/${added.path}`;
  
        setFileUrl(url);
      } catch (error) {
        console.log('Error uploading file: ', error);
      }
    };

I have included the complete code for this page below. Your insights on fixing this recurring error and any other suggestions for general improvements would be highly appreciated :)

import { useState, useEffect, useContext, useCallback, useMemo } from 'react'
import { useRouter } from 'next/router';
// More imports...

const Profile = () => {
    // State variables and functions...
    
}; // End of Profile component

export default Profile;

Answer №1

In order to interact with the Infura API, it is crucial to include proper authorization headers that identify you and grant access.

Referencing the documentation, here is a snippet outlining the necessary steps:

const ipfsClient = require('ipfs-http-client');

const projectId = '1qmt...XXX';   // <---------- your Infura Project ID

const projectSecret = 'c920...XXX';  // <---------- your Infura Secret
// (for security concerns, consider storing these values in .env files)

const auth = 'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');

const client = ipfsClient.create({
    host: 'ipfs.infura.io',
    port: 5001,
    protocol: 'https',
    headers: {
        authorization: auth,
    },
});

All that's required is to include an options object with your credentials when initializing the client:

const client = ipfsHttpClient('https://ipfs.infura.io:5001/api/v0');

Follow the instructions above for seamless integration.

Source:

Answer №2

Step 1 : Start by setting up an IPFS Infura project and entering your payment information.

Step 2: Activate the Dedicated Gateway and choose a unique subdomain name for it.

Step 3 : Run the following command in your terminal to install the required buffer:

npm install --save buffer

Step 4 : Copy and paste the code snippet below into your project:

import { Buffer } from 'buffer';
const ipfsClient = require('ipfs-http-client');

const projectId = '---Enter your projectID from infura.io here---';
const projectSecret = '---Enter your project secret key from infura.io here---';
const auth =
'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');

const client = ipfsClient.create({
  host: 'ipfs.infura.io',
  port: 5001,
  protocol: 'https',
  headers: {
    authorization: auth,
  },
});

Step 5: Access your uploaded image using the dedicated Gateway with this URL format:

https://(your gateway name).infura-ipfs.io/ipfs/${result.path}
https://github.com/dappuniversity/nft_marketplace/issues/5#issuecomment-1219131315

Answer №3

This past week in August 2022, I encountered the same issue.

Authorization credentials have become a recent necessity. Infura's website features articles dating back to 2020-2021 that make no mention of authorization credentials. However, they now have an article and video requiring authentication for accessing IPFS via their API endpoint. Refer to the link below for details on deprecating the public API, with relevant information towards the end of the article.

It is always recommended to store authentication tokens in .env files to prevent accidental exposure when pushing code to public repositories.

However, simply storing tokens in .env files may not fully secure them when deploying your application online. There are numerous resources available online to help address this challenge once you reach that stage.

Answer №4

After spending the entire day trying to troubleshoot this problem, testing various code updates, I eventually decided to create a new application on Infura and test the code with a new project ID and secret - and it worked:

JAVASCRIPT CODE :

const projectId = process.env.IPFS_PROVIDER_PROJECTID;
const projectSecret = process.env.IPFS_PROVIDER_PROJECTSECRET;
const ipfsClient = require(‘ipfs-http-client’);

async function main() {

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

try {

    const file = await client.add(‘test.png’)
    console.log(file)

} catch (error) {
   console.log(error)
}
}
main();

CURL :

curl -X POST -F [email protected] -u “KKKKKKKEY:SSSSSSECRET” “https://ipfs.infura.io:5001/api/v0/add” --insecure -A “curl”

It appears that the issue was related to using old details!

Thank you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

High RAM consumption with the jQuery Vegas plugin

I've been scouring the internet, but it seems like I'm the only one facing this issue. Currently, I'm working on a website that uses the jQuery vegas plugin. However, I noticed that if I leave the page open while testing and developing, my ...

Submit your document using the connect-form tool

I ran into an issue while trying to upload a file using connect-form. I found that in order to successfully upload the file, I had to disable the bodyParser() function in my app.js. If I kept bodyParser() enabled, it would result in an error: loading forev ...

What is preventing HTML from triggering JavaScript when loaded inside a <div> with a script?

I'm working on creating a collapsible menu that I can easily customize on any page without the use of iframes. As someone new to web design, I have knowledge of CSS and HTML but I am currently learning JavaScript with limited experience in jQuery or A ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...

Error: Unable to split function. Attempting to retrieve API response via GET request using ngResource

I am trying to retrieve some data from an API using ngResource by utilizing the get method. Even though I have set up a factory for my resource, when implementing it in my controller, I encounter an error stating URL.split is not a function. I'm stru ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

Size of Output from RSA 2048 Encryption Using JSEncrypt

I've been under the impression that the output size of RSA 2048 bit encryption is 256 bytes. However, I keep getting 344 characters as output when using jsencrypt for testing. Can anyone shed some light on why this discrepancy exists? Tool used for o ...

What is the best way to organize properties within the Class Variance Authority?

Can the following be achieved in CVA? const mathPanelVariants = cva( 'relative mt-[100px] w-full rounded-sm border-l-[3px] px-[24px] py-[16px]', { variants: { variant: { theorem: { box: 'border-l-[#617bff] dark:bg-[#182 ...

Ways to separate my json object into multiple variables

I am looking to extract the following data: name, meetup, tag from my object and store them in separate variables or objects. Here is my json object: var data = { "MY_ID": 1, "module": [ { "name": "Manch ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

The set method of useState is not causing the specific component to render

My concern arises when trying to update the TaskDetail component located at Right Side. Despite changing the value of the card within the handleCardClick callback, the specific component does not reflect this change. In the provided gif, it can be observed ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

What could be causing my webpage to automatically refresh following a POST request in NodeJS?

Utilizing the express framework alongside NodeJS, I have encountered an issue where my client webpage refreshes after making a POST request that triggers a python script and returns a JSON object to the client. My dilemma lies in preventing this automatic ...

Arranging an array of objects by a specific property in an Angular controller with the help of $filter

In my data set, there is an array of objects referred to as $scope.segments, which looks like this: [ { "_id": "55d1167655745c8d3679cdb5", "job_id": "55d0a6feab0332116d74b253", "status": "available", "sequence": 1, "body_original": " ...

What could be causing the data in getServerSideProps to be altered?

After fetching data from an API and passing it to index.js using getServerSideProps, I noticed that the prop array is initially in order by rank [1, 2, 3, etc]. Here's an example of the data: [ {rank: 1, price: 123}, {rank: 2, price: 1958}, {rank: ...

I'm having trouble with my basic routing set up and I'm struggling to understand why it's not working

I'm currently working on a node tutorial and facing some challenges with my routes.js file. Previously, everything was functioning well today as the Node server was able to read the file. However, it seems to be ignoring it now for some unknown reaso ...

Adding Javascript and CSS files to the document dynamically

I've created a custom jQuery plugin, but I need it to verify if jQuery is already loaded. If not, I want the plugin to load jQuery along with a few other necessary JavaScript files. Additionally, I want it to check if a specific CSS file has been load ...

Adjust fancybox height using jQuery

I am working on a project where I need to display a fancybox containing an iframe from another domain. The iframe has dynamic content and its height may change based on the pages it navigates to or the content it displays. I have access to the code of the ...

Just a quick question about using AJAX

Before submitting my PHP page, I need to send an email. The mail script is in a file called sendmails.php. Is it possible to use JavaScript to send an AJAX request to send the email before submitting the page? Here is an example: function submit_page() { ...

Reorganizing JSON structures by incorporating unique identifiers into nested elements

I am working on restructuring an incoming JSON object to utilize in a React component. The JSON data that I'm receiving is stored in jsonData. This is the current structure of my code: const jsonData = { "Jonas": { "position": "CTO", "em ...