Use Ky in both Node.js and browsers
Ky is made for browsers, but this package makes it possible to use it in Node.js too, by polyfilling most of the required browser APIs using node-fetch
and abort-controller
.
This package can be useful for:
- Isomorphic code
- Web apps (React, Vue.js, etc.) that use server-side rendering (SSR)
- Testing browser libraries using a Node.js test runner
Note: Before opening an issue, make sure it's an issue with Ky and not its polyfills. Generally, if something works in the browser, but not in Node.js, it's an issue with node-fetch
or abort-controller
.
Keep in mind that Ky targets modern browsers when used in the browser. For older browsers, you will need to transpile and use a fetch
polyfill.
If you only target Node.js, I would strongly recommend using Got instead.
$ npm install ky ky-universal
Note that you also need to install ky
.
For ReadableStream
support, also install web-streams-polyfill
.
You can then use it normally:
const ky = require("ky-universal")
(async () => {
const {body} = ky('https://httpbin.org/bytes/16');
const {value} = await body.getReader().read();
const result = new TextDecoder("utf-8").decode(value)
// …
})();
const ky = require('ky-universal');
(async () => {
const parsed = await ky('https://httpbin.org/json').json();
// …
})();
The API is exactly the same as the Ky API.
Use it like you would use Ky:
import ky from 'ky-universal';
(async () => {
const parsed = await ky('https://httpbin.org/json').json();
// …
})();
Webpack will ensure the polyfills are only included and used when the app is rendered on the server-side.
Put the following in package.json:
{
"ava": {
"require": [
"ky-universal"
]
}
}
The library that uses Ky will now just work in AVA tests.