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?
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?
2 Answers
Reset to default 4@NasiruddinSaiyed answer is a bit outdated so here is the 2021 answer:
NextJS server-side-polyfills docs
Server-Side Polyfills
In addition to fetch() on the client side, Next.js polyfills fetch() in the Node.js environment. You can use fetch() on your server code (such as getStaticProps) without using polyfills such as isomorphic-unfetch or node-fetch.
So it should just work out of the box
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 ponent.
Example ::
`import fetch from 'isomorphic-unfetch';`
// ... Index ponent code
Index.getInitialProps = async function() {
const res = await fetch('https://api.tvmaze./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!!