Best way to conditionally polyfill fetch #1751
-
Node.js had natively added fetch, but older versions don't accept it by default. node-fetch provides this in the main README:
Regards. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
My personal suggestion would just be to tell folks to upgrade their NodeJS version. "engine": {
"node": ">=18"
} The alternative is that you let the clients bring in their own fetch impl from wherever they choose to bring in. weather it be undici, node-fetch v3 (or v2 for cjs) so you could let them decide for themself what they want to bring in. they might already have a dependency on undici, so it would be unnecessary to add node-fetch into the mix as well.
No, but I have tough about doing that. it would certainly be a breaking change cuz they don't work exactly the same, like passing a Agent as an option for example. if you want to support NodeJS v16 (which is the latest LTS then i would have opt'ed for using undici instead that's more spec compatible and uses web streams instead of node streams. if (!globalThis.fetch) {
const { fetch, FormData, Headers, Request, Response } = await import('undici')
Object.assign(globalThis, { fetch, FormData, Headers, Request, Response })
} But i would also have added undici to optional dependencies so folks with newer NodeJS version don't need to download it in vain One thing if you are working with Blob/Files and wish to send multiple large files using FormData is to use |
Beta Was this translation helpful? Give feedback.
-
Thank you for the detailed response. Upgrading Node.js would be ideal, but even on a recent project there was a compatibility issue that meant I end up using Node 17, so it may be a while longer until that method can be relied upon. I will check out undici. The code you provided seems like a good alternative polyfill. Regards. |
Beta Was this translation helpful? Give feedback.
My personal suggestion would just be to tell folks to upgrade their NodeJS version.
Adding this to your package.json
The alternative is that you let the clients bring in their own fetch impl from wherever they choose to bring in. weather it be undici, node-fetch v3 (or v2 for cjs) so you could let them decide for themself what they want to bring in. they might already have a dependency on undici, so it would be unnecessary to add node-fetch into the mix as well.
No, but I have tough about doing that. it would certainly be a breaking …