└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # This Package Uses Fetch 2 | 3 | If you've landed here from a JavaScript package's documentation, it means that the aforementioned package uses [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) internally, and wants to help you polyfill it if needed. 4 | 5 | For more information on why we created this document, [visit our blog post](https://www.builder.io/blog/stop-polyfilling-fetch-in-your-npm-package). 6 | 7 | ## Do I need a polyfill? 8 | 9 | Here's a brief definition of a [polyfill](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill): 10 | 11 | > A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older environments that do not natively support it. 12 | 13 | In the case of `fetch`, this will primarily be: 14 | 15 | - Browsers: Opera Mini & IE 16 | - Server: Node v17 or lower 17 | 18 | Therefore, if you fit one of the following scenarios: 19 | - plan on using the package in a webapp, and you have data that indicates that your users might be on these older browsers (e.g. by importing your analytics into https://caniuse.com/ciu/import) 20 | - plan on using the package in a Node.js server that's on v17 or below 21 | 22 | then you might want to keep reading. Otherwise, you don't need to do anything! 23 | 24 | ## Polyfills 25 | 26 | There are many polyfills out there, but here are the ones we'll recommend: 27 | 28 | - node implementation: [node-fetch](https://github.com/bitinn/node-fetch) 29 | - browser polyfill: [whatwg-fetch](https://github.com/github/fetch) 30 | 31 | ## Adding polyfills 32 | 33 | To polyfill fetch in the global scope, you'll have to do the following in your application's entry point (or at least, before the package that needs fetch is imported): 34 | 35 | 36 | - server: 37 | 38 | ```ts 39 | import fetch from 'node-fetch'; 40 | globalThis.fetch = fetch; 41 | 42 | // only import the package _after_ 43 | import packageThatUsesFetch from 'package-that-uses-fetch'; 44 | ``` 45 | 46 | - browser: 47 | 48 | ```ts 49 | // browser 50 | import 'whatwg-fetch'; 51 | 52 | // only import the package _after_ 53 | import packageThatUsesFetch from 'package-that-uses-fetch'; 54 | ``` 55 | 56 | 57 | From then on, you're free to use the package as you see fit. 58 | --------------------------------------------------------------------------------