Using js-ipfs through file:// protocol

Hi. Is there a way to use js-ipfs solely on the client side? E.g. via file:// protocol?
If not, is there a tutorial about how to use http-api via file:// protocol?

1 Like

I’m trying this:

<script>
    fetch('http://127.0.0.1:5001/api/v0/object/data',
        {
            method: 'POST',
            mode: 'no-cors',
            headers: {
                'Accept': '*/*',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: "arg=QmeomffUNfmQy76CQGy9NdmqEnnHU9soCexBnGU3ezPHVH"
        }
    )
        .then((response) => response.text())
        .then(data => console.log(data))
        .catch((error) => {
            console.error(error)
        })
</script>

But it gives me “net::ERR_ABORTED 403 (Forbidden)”

fetch requests sent from file:// will have Origin: null and that is why you get 403 Forbidden.

This is a security feature, blocking sandboxed iframes without allow-same-origin on regular websites from accessing HTTP API on your localhost. file:// happens to send the same Origin, and also gets blocked.

Rule of thumb: don’t use file://, instead load your page via a local HTTP server. That ensures correct Origin and enables you to leverage CORS for access control.

You don’t need to install Nginx to play with this, any one-line server will do.
For example, if you use Node:

npx http-server . -p 3000 -c-1

A longer list of similar one-liners can be found here.

1 Like

Thanks for the tips.
Will origin be null too if I access a page through ipfs:// on Brave?
I’m trying to make a dynamic one page web app that would read data from a block chain where the first block comes from IPNS

David

I Just tried using a server and still got the same error. I wonder if I’m doing something wrong with the fetch API.

When you access resources via ipfs:// then an unique Origin will be created for each content root (CID). You can inspect the origin of every web page via window.location.origin. This applies to https:// as well.

If you want your web page to have access to the API port of your local IPFS Node, you need to safelist that specific Origin via CORS.

For example, to allow API access to http://localhost:3000 you would set:

ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["http://localhost:3000", "http://127.0.0.1:5001"]'
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "POST"]'
2 Likes