Skip to content

Instantly share code, notes, and snippets.

@thinkverse
Created April 24, 2023 20:55
Show Gist options
  • Save thinkverse/8b7f26e8c4a2c76e5f260b33521e9e72 to your computer and use it in GitHub Desktop.
Save thinkverse/8b7f26e8c4a2c76e5f260b33521e9e72 to your computer and use it in GitHub Desktop.
A undici fetch Polyfill shamelessly ripped from Next.js
import Undici from "undici";
// Polyfill fetch() in the Node.js environment
// Simplified from https://github.com/vercel/next.js/blob/canary/packages/next/src/server/node-polyfill-fetch.ts
if (!global.fetch) {
function getFetchImpl() {
return Undici;
}
global.fetch = (...args) => {
const fetchImpl = getFetchImpl();
fetchImpl.setGlobalDispatcher(new fetchImpl.Agent({ pipelining: 0 }))
return fetchImpl.fetch(...args);
}
Object.defineProperties(global, {
Headers: {
get() {
return getFetchImpl().Headers
},
},
Request: {
get() {
return getFetchImpl().Request
},
},
Response: {
get() {
return getFetchImpl().Response
},
},
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment