@whatwg-node/fetch
A ponyfill package for the Fetch Standard. If your JavaScript
environment doesn't implement this standard natively, this package automatically ponyfills the
missing parts, and export them as a module; otherwise it exports the native ones without touching
the environment's internals. It also exports some additional standard APIs that are required by the
Fetch Standard.
Installation
yarn add @whatwg-node/fetch
Why Fetch API and why this ponyfill in general?
If you are building a JavaScript library, and you want it to support all JavaScript environments not
only Node.js. Fetch API is the best choice for you. Because it's a standard, and it's implemented by
the most environments out there expect Node.js :). So you can use Fetch API in your library, and
your users can use it in their browsers, Deno, Bun, Cloudflare Works, and in Node.js.
This is how we support all JavaScript environments in
GraphQL Yoga.
In GraphQL Yoga, we don't care which JavaScript environment you prefer, we support all of them.
Why we should still use these for Node.js even if it already implements them natively
Even if newer Node.js already implements Fetch API and Data Text Encoding API natively, we still
recommend to use this package, because this package implements them for Node.js in more efficient
way.
Handling file uploads with Fetch API
import { Request } from '@whatwg-node/fetch'
http.createServer(async (req, res) => {
const request = new Request(req)
const formData = await request.formData()
const file = formData.get('file')
})
If you want to limit the size of the multipart form data, you can use createFetch. See the
API section for more details.
API
The following are exported by this package:
WHATWG Fetch Standard
Web Streams API
URL Standard
Data Types
Data Encoding/Decoding API
Web Crypto API
Create variations of the implementation
createFetch allows you to create an API with some specific flags that are not available in the
actual API.
Limit the multipart form data size
This is useful if you parse the multipart request bodies with .formData().
import { createFetch } from '@whatwg-node/fetch'
const fetchAPI = createFetch({
formDataLimits: {
fileSize: 1000000,
files: 10,
fieldSize: 1000000,
headerSize: 1000000
}
})
http.createServer(async (req, res) => {
const request = new Request(req)
const formData = await request.formData()
const file = formData.get('file')
})