1# make-fetch-happen [![npm version](https://img.shields.io/npm/v/make-fetch-happen.svg)](https://npm.im/make-fetch-happen) [![license](https://img.shields.io/npm/l/make-fetch-happen.svg)](https://npm.im/make-fetch-happen) [![Travis](https://img.shields.io/travis/zkat/make-fetch-happen.svg)](https://travis-ci.org/zkat/make-fetch-happen) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/zkat/make-fetch-happen?svg=true)](https://ci.appveyor.com/project/zkat/make-fetch-happen) [![Coverage Status](https://coveralls.io/repos/github/zkat/make-fetch-happen/badge.svg?branch=latest)](https://coveralls.io/github/zkat/make-fetch-happen?branch=latest) 2 3 4[`make-fetch-happen`](https://github.com/zkat/make-fetch-happen) is a Node.js 5library that wraps [`node-fetch-npm`](https://github.com/npm/node-fetch-npm) with additional 6features [`node-fetch`](https://github.com/bitinn/node-fetch) doesn't intend to include, including HTTP Cache support, request 7pooling, proxies, retries, [and more](#features)! 8 9## Install 10 11`$ npm install --save make-fetch-happen` 12 13## Table of Contents 14 15* [Example](#example) 16* [Features](#features) 17* [Contributing](#contributing) 18* [API](#api) 19 * [`fetch`](#fetch) 20 * [`fetch.defaults`](#fetch-defaults) 21 * [`node-fetch` options](#node-fetch-options) 22 * [`make-fetch-happen` options](#extra-options) 23 * [`opts.cacheManager`](#opts-cache-manager) 24 * [`opts.cache`](#opts-cache) 25 * [`opts.proxy`](#opts-proxy) 26 * [`opts.noProxy`](#opts-no-proxy) 27 * [`opts.ca, opts.cert, opts.key`](#https-opts) 28 * [`opts.maxSockets`](#opts-max-sockets) 29 * [`opts.retry`](#opts-retry) 30 * [`opts.onRetry`](#opts-onretry) 31 * [`opts.integrity`](#opts-integrity) 32* [Message From Our Sponsors](#wow) 33 34### Example 35 36```javascript 37const fetch = require('make-fetch-happen').defaults({ 38 cacheManager: './my-cache' // path where cache will be written (and read) 39}) 40 41fetch('https://registry.npmjs.org/make-fetch-happen').then(res => { 42 return res.json() // download the body as JSON 43}).then(body => { 44 console.log(`got ${body.name} from web`) 45 return fetch('https://registry.npmjs.org/make-fetch-happen', { 46 cache: 'no-cache' // forces a conditional request 47 }) 48}).then(res => { 49 console.log(res.status) // 304! cache validated! 50 return res.json().then(body => { 51 console.log(`got ${body.name} from cache`) 52 }) 53}) 54``` 55 56### Features 57 58* Builds around [`node-fetch`](https://npm.im/node-fetch) for the core [`fetch` API](https://fetch.spec.whatwg.org) implementation 59* Request pooling out of the box 60* Quite fast, really 61* Automatic HTTP-semantics-aware request retries 62* Cache-fallback automatic "offline mode" 63* Proxy support (http, https, socks, socks4, socks5) 64* Built-in request caching following full HTTP caching rules (`Cache-Control`, `ETag`, `304`s, cache fallback on error, etc). 65* Customize cache storage with any [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache)-compliant `Cache` instance. Cache to Redis! 66* Node.js Stream support 67* Transparent gzip and deflate support 68* [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) support 69* Literally punches nazis 70* (PENDING) Range request caching and resuming 71 72### Contributing 73 74The make-fetch-happen team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. 75 76All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other. 77 78Please refer to the [Changelog](CHANGELOG.md) for project history details, too. 79 80Happy hacking! 81 82### API 83 84#### <a name="fetch"></a> `> fetch(uriOrRequest, [opts]) -> Promise<Response>` 85 86This function implements most of the [`fetch` API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch): given a `uri` string or a `Request` instance, it will fire off an http request and return a Promise containing the relevant response. 87 88If `opts` is provided, the [`node-fetch`-specific options](#node-fetch-options) will be passed to that library. There are also [additional options](#extra-options) specific to make-fetch-happen that add various features, such as HTTP caching, integrity verification, proxy support, and more. 89 90##### Example 91 92```javascript 93fetch('https://google.com').then(res => res.buffer()) 94``` 95 96#### <a name="fetch-defaults"></a> `> fetch.defaults([defaultUrl], [defaultOpts])` 97 98Returns a new `fetch` function that will call `make-fetch-happen` using `defaultUrl` and `defaultOpts` as default values to any calls. 99 100A defaulted `fetch` will also have a `.defaults()` method, so they can be chained. 101 102##### Example 103 104```javascript 105const fetch = require('make-fetch-happen').defaults({ 106 cacheManager: './my-local-cache' 107}) 108 109fetch('https://registry.npmjs.org/make-fetch-happen') // will always use the cache 110``` 111 112#### <a name="node-fetch-options"></a> `> node-fetch options` 113 114The following options for `node-fetch` are used as-is: 115 116* method 117* body 118* redirect 119* follow 120* timeout 121* compress 122* size 123 124These other options are modified or augmented by make-fetch-happen: 125 126* headers - Default `User-Agent` set to make-fetch happen. `Connection` is set to `keep-alive` or `close` automatically depending on `opts.agent`. 127* agent 128 * If agent is null, an http or https Agent will be automatically used. By default, these will be `http.globalAgent` and `https.globalAgent`. 129 * If [`opts.proxy`](#opts-proxy) is provided and `opts.agent` is null, the agent will be set to an appropriate proxy-handling agent. 130 * If `opts.agent` is an object, it will be used as the request-pooling agent argument for this request. 131 * If `opts.agent` is `false`, it will be passed as-is to the underlying request library. This causes a new Agent to be spawned for every request. 132 133For more details, see [the documentation for `node-fetch` itself](https://github.com/bitinn/node-fetch#options). 134 135#### <a name="extra-options"></a> `> make-fetch-happen options` 136 137make-fetch-happen augments the `node-fetch` API with additional features available through extra options. The following extra options are available: 138 139* [`opts.cacheManager`](#opts-cache-manager) - Cache target to read/write 140* [`opts.cache`](#opts-cache) - `fetch` cache mode. Controls cache *behavior*. 141* [`opts.proxy`](#opts-proxy) - Proxy agent 142* [`opts.noProxy`](#opts-no-proxy) - Domain segments to disable proxying for. 143* [`opts.ca, opts.cert, opts.key, opts.strictSSL`](#https-opts) 144* [`opts.localAddress`](#opts-local-address) 145* [`opts.maxSockets`](#opts-max-sockets) 146* [`opts.retry`](#opts-retry) - Request retry settings 147* [`opts.onRetry`](#opts-onretry) - a function called whenever a retry is attempted 148* [`opts.integrity`](#opts-integrity) - [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) metadata. 149 150#### <a name="opts-cache-manager"></a> `> opts.cacheManager` 151 152Either a `String` or a `Cache`. If the former, it will be assumed to be a `Path` to be used as the cache root for [`cacache`](https://npm.im/cacache). 153 154If an object is provided, it will be assumed to be a compliant [`Cache` instance](https://developer.mozilla.org/en-US/docs/Web/API/Cache). Only `Cache.match()`, `Cache.put()`, and `Cache.delete()` are required. Options objects will not be passed in to `match()` or `delete()`. 155 156By implementing this API, you can customize the storage backend for make-fetch-happen itself -- for example, you could implement a cache that uses `redis` for caching, or simply keeps everything in memory. Most of the caching logic exists entirely on the make-fetch-happen side, so the only thing you need to worry about is reading, writing, and deleting, as well as making sure `fetch.Response` objects are what gets returned. 157 158You can refer to `cache.js` in the make-fetch-happen source code for a reference implementation. 159 160**NOTE**: Requests will not be cached unless their response bodies are consumed. You will need to use one of the `res.json()`, `res.buffer()`, etc methods on the response, or drain the `res.body` stream, in order for it to be written. 161 162The default cache manager also adds the following headers to cached responses: 163 164* `X-Local-Cache`: Path to the cache the content was found in 165* `X-Local-Cache-Key`: Unique cache entry key for this response 166* `X-Local-Cache-Hash`: Specific integrity hash for the cached entry 167* `X-Local-Cache-Time`: UTCString of the cache insertion time for the entry 168 169Using [`cacache`](https://npm.im/cacache), a call like this may be used to 170manually fetch the cached entry: 171 172```javascript 173const h = response.headers 174cacache.get(h.get('x-local-cache'), h.get('x-local-cache-key')) 175 176// grab content only, directly: 177cacache.get.byDigest(h.get('x-local-cache'), h.get('x-local-cache-hash')) 178``` 179 180##### Example 181 182```javascript 183fetch('https://registry.npmjs.org/make-fetch-happen', { 184 cacheManager: './my-local-cache' 185}) // -> 200-level response will be written to disk 186 187fetch('https://npm.im/cacache', { 188 cacheManager: new MyCustomRedisCache(process.env.PORT) 189}) // -> 200-level response will be written to redis 190``` 191 192A possible (minimal) implementation for `MyCustomRedisCache`: 193 194```javascript 195const bluebird = require('bluebird') 196const redis = require("redis") 197bluebird.promisifyAll(redis.RedisClient.prototype) 198class MyCustomRedisCache { 199 constructor (opts) { 200 this.redis = redis.createClient(opts) 201 } 202 match (req) { 203 return this.redis.getAsync(req.url).then(res => { 204 if (res) { 205 const parsed = JSON.parse(res) 206 return new fetch.Response(parsed.body, { 207 url: req.url, 208 headers: parsed.headers, 209 status: 200 210 }) 211 } 212 }) 213 } 214 put (req, res) { 215 return res.buffer().then(body => { 216 return this.redis.setAsync(req.url, JSON.stringify({ 217 body: body, 218 headers: res.headers.raw() 219 })) 220 }).then(() => { 221 // return the response itself 222 return res 223 }) 224 } 225 'delete' (req) { 226 return this.redis.unlinkAsync(req.url) 227 } 228} 229``` 230 231#### <a name="opts-cache"></a> `> opts.cache` 232 233This option follows the standard `fetch` API cache option. This option will do nothing if [`opts.cacheManager`](#opts-cache-manager) is null. The following values are accepted (as strings): 234 235* `default` - Fetch will inspect the HTTP cache on the way to the network. If there is a fresh response it will be used. If there is a stale response a conditional request will be created, and a normal request otherwise. It then updates the HTTP cache with the response. If the revalidation request fails (for example, on a 500 or if you're offline), the stale response will be returned. 236* `no-store` - Fetch behaves as if there is no HTTP cache at all. 237* `reload` - Fetch behaves as if there is no HTTP cache on the way to the network. Ergo, it creates a normal request and updates the HTTP cache with the response. 238* `no-cache` - Fetch creates a conditional request if there is a response in the HTTP cache and a normal request otherwise. It then updates the HTTP cache with the response. 239* `force-cache` - Fetch uses any response in the HTTP cache matching the request, not paying attention to staleness. If there was no response, it creates a normal request and updates the HTTP cache with the response. 240* `only-if-cached` - Fetch uses any response in the HTTP cache matching the request, not paying attention to staleness. If there was no response, it returns a network error. (Can only be used when request’s mode is "same-origin". Any cached redirects will be followed assuming request’s redirect mode is "follow" and the redirects do not violate request’s mode.) 241 242(Note: option descriptions are taken from https://fetch.spec.whatwg.org/#http-network-or-cache-fetch) 243 244##### Example 245 246```javascript 247const fetch = require('make-fetch-happen').defaults({ 248 cacheManager: './my-cache' 249}) 250 251// Will error with ENOTCACHED if we haven't already cached this url 252fetch('https://registry.npmjs.org/make-fetch-happen', { 253 cache: 'only-if-cached' 254}) 255 256// Will refresh any local content and cache the new response 257fetch('https://registry.npmjs.org/make-fetch-happen', { 258 cache: 'reload' 259}) 260 261// Will use any local data, even if stale. Otherwise, will hit network. 262fetch('https://registry.npmjs.org/make-fetch-happen', { 263 cache: 'force-cache' 264}) 265``` 266 267#### <a name="opts-proxy"></a> `> opts.proxy` 268 269A string or `url.parse`-d URI to proxy through. Different Proxy handlers will be 270used depending on the proxy's protocol. 271 272Additionally, `process.env.HTTP_PROXY`, `process.env.HTTPS_PROXY`, and 273`process.env.PROXY` are used if present and no `opts.proxy` value is provided. 274 275(Pending) `process.env.NO_PROXY` may also be configured to skip proxying requests for all, or specific domains. 276 277##### Example 278 279```javascript 280fetch('https://registry.npmjs.org/make-fetch-happen', { 281 proxy: 'https://corporate.yourcompany.proxy:4445' 282}) 283 284fetch('https://registry.npmjs.org/make-fetch-happen', { 285 proxy: { 286 protocol: 'https:', 287 hostname: 'corporate.yourcompany.proxy', 288 port: 4445 289 } 290}) 291``` 292 293#### <a name="opts-no-proxy"></a> `> opts.noProxy` 294 295If present, should be a comma-separated string or an array of domain extensions 296that a proxy should _not_ be used for. 297 298This option may also be provided through `process.env.NO_PROXY`. 299 300#### <a name="https-opts"></a> `> opts.ca, opts.cert, opts.key, opts.strictSSL` 301 302These values are passed in directly to the HTTPS agent and will be used for both 303proxied and unproxied outgoing HTTPS requests. They mostly correspond to the 304same options the `https` module accepts, which will be themselves passed to 305`tls.connect()`. `opts.strictSSL` corresponds to `rejectUnauthorized`. 306 307#### <a name="opts-local-address"></a> `> opts.localAddress` 308 309Passed directly to `http` and `https` request calls. Determines the local 310address to bind to. 311 312#### <a name="opts-max-sockets"></a> `> opts.maxSockets` 313 314Default: 15 315 316Maximum number of active concurrent sockets to use for the underlying 317Http/Https/Proxy agents. This setting applies once per spawned agent. 318 31915 is probably a _pretty good value_ for most use-cases, and balances speed 320with, uh, not knocking out people's routers. 321 322#### <a name="opts-retry"></a> `> opts.retry` 323 324An object that can be used to tune request retry settings. Retries will only be attempted on the following conditions: 325 326* Request method is NOT `POST` AND 327* Request status is one of: `408`, `420`, `429`, or any status in the 500-range. OR 328* Request errored with `ECONNRESET`, `ECONNREFUSED`, `EADDRINUSE`, `ETIMEDOUT`, or the `fetch` error `request-timeout`. 329 330The following are worth noting as explicitly not retried: 331 332* `getaddrinfo ENOTFOUND` and will be assumed to be either an unreachable domain or the user will be assumed offline. If a response is cached, it will be returned immediately. 333* `ECONNRESET` currently has no support for restarting. It will eventually be supported but requires a bit more juggling due to streaming. 334 335If `opts.retry` is `false`, it is equivalent to `{retries: 0}` 336 337If `opts.retry` is a number, it is equivalent to `{retries: num}` 338 339The following retry options are available if you want more control over it: 340 341* retries 342* factor 343* minTimeout 344* maxTimeout 345* randomize 346 347For details on what each of these do, refer to the [`retry`](https://npm.im/retry) documentation. 348 349##### Example 350 351```javascript 352fetch('https://flaky.site.com', { 353 retry: { 354 retries: 10, 355 randomize: true 356 } 357}) 358 359fetch('http://reliable.site.com', { 360 retry: false 361}) 362 363fetch('http://one-more.site.com', { 364 retry: 3 365}) 366``` 367 368#### <a name="opts-onretry"></a> `> opts.onRetry` 369 370A function called whenever a retry is attempted. 371 372##### Example 373 374```javascript 375fetch('https://flaky.site.com', { 376 onRetry() { 377 console.log('we will retry!') 378 } 379}) 380``` 381 382#### <a name="opts-integrity"></a> `> opts.integrity` 383 384Matches the response body against the given [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) metadata. If verification fails, the request will fail with an `EINTEGRITY` error. 385 386`integrity` may either be a string or an [`ssri`](https://npm.im/ssri) `Integrity`-like. 387 388##### Example 389 390```javascript 391fetch('https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-1.0.0.tgz', { 392 integrity: 'sha1-o47j7zAYnedYFn1dF/fR9OV3z8Q=' 393}) // -> ok 394 395fetch('https://malicious-registry.org/make-fetch-happen/-/make-fetch-happen-1.0.0.tgz', { 396 integrity: 'sha1-o47j7zAYnedYFn1dF/fR9OV3z8Q=' 397}) // Error: EINTEGRITY 398``` 399 400### <a name="wow"></a> Message From Our Sponsors 401 402![](stop.gif) 403 404![](happening.gif) 405