I've got following use case scenario. I have web worker within which I need to fetch image that is located in NextJS public
folder in order to convert it to blob.
Right now executing fetch('public/images/myImage.png');
or fetch('/images/myImage.png');
leads to an error:
Error: TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Failed to parse URL from /images/ui/background_fire.jpg
So I assume it is not being resolved correctly like it would in say src
of an image?
As per official Docs you need to use isomorphic-unfetch.
It's a simple implementation of the browser fetch API, but works both in client and server environments.
Install it
$npm install --save isomorphic-unfetch
or
$yarn add isomorphic-unfetch
Now you can use it in from getInitialProps
to any where in your component.
Example ::
`import fetch from 'isomorphic-unfetch';`
// ... Index component code
Index.getInitialProps = async function() {
const res = await fetch('https://api.tvmaze.com/search/shows?q=batman');
const data = await res.json();
console.log(`Show data fetched. Count: ${data.length}`);
return {
shows: data.map(entry => entry.show)
};
};
Happy coding!!