Détail du package

make-fetch-happen

npm89mISC14.0.3

Opinionated, caching, retrying fetch client

http, request, fetch, mean girls

readme

make-fetch-happen

npm version license Travis Coverage Status

make-fetch-happen is a Node.js library that wraps minipass-fetch with additional features minipass-fetch doesn't intend to include, including HTTP Cache support, request pooling, proxies, retries, and more!

Install

$ npm install --save make-fetch-happen

Table of Contents

Example

const fetch = require('make-fetch-happen').defaults({
  cachePath: './my-cache' // path where cache will be written (and read)
})

fetch('https://registry.npmjs.org/make-fetch-happen').then(res => {
  return res.json() // download the body as JSON
}).then(body => {
  console.log(`got ${body.name} from web`)
  return fetch('https://registry.npmjs.org/make-fetch-happen', {
    cache: 'no-cache' // forces a conditional request
  })
}).then(res => {
  console.log(res.status) // 304! cache validated!
  return res.json().then(body => {
    console.log(`got ${body.name} from cache`)
  })
})

Features

  • Builds around minipass-fetch for the core fetch API implementation
  • Request pooling out of the box
  • Quite fast, really
  • Automatic HTTP-semantics-aware request retries
  • Cache-fallback automatic "offline mode"
  • Built-in request caching following full HTTP caching rules (Cache-Control, ETag, 304s, cache fallback on error, etc).
  • Node.js Stream support
  • Transparent gzip and deflate support
  • Subresource Integrity support
  • Proxy support (http, https, socks, socks4, socks5. via @npmcli/agent)
  • DNS cache (via (@npmcli/agent)

> fetch(uriOrRequest, [opts]) -> Promise<Response>

This function implements most of the fetch API: given a uri string or a Request instance, it will fire off an http request and return a Promise containing the relevant response.

If opts is provided, the minipass-fetch-specific options will be passed to that library. There are also additional options specific to make-fetch-happen that add various features, such as HTTP caching, integrity verification, proxy support, and more.

Example
fetch('https://google.com').then(res => res.buffer())

> fetch.defaults([defaultUrl], [defaultOpts])

Returns a new fetch function that will call make-fetch-happen using defaultUrl and defaultOpts as default values to any calls.

A defaulted fetch will also have a .defaults() method, so they can be chained.

Example
const fetch = require('make-fetch-happen').defaults({
  cachePath: './my-local-cache'
})

fetch('https://registry.npmjs.org/make-fetch-happen') // will always use the cache

> minipass-fetch options

The following options for minipass-fetch are used as-is:

  • method
  • body
  • redirect
  • follow
  • timeout
  • compress
  • size

These other options are modified or augmented by make-fetch-happen:

  • headers - Default User-Agent set to make-fetch happen. Connection is set to keep-alive or close automatically depending on opts.agent.

For more details, see the documentation for minipass-fetch itself.

> make-fetch-happen options

make-fetch-happen augments the minipass-fetch API with additional features available through extra options. The following extra options are available:

> opts.cachePath

A string Path to be used as the cache root for cacache.

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.

The default cache manager also adds the following headers to cached responses:

  • X-Local-Cache: Path to the cache the content was found in
  • X-Local-Cache-Key: Unique cache entry key for this response
  • X-Local-Cache-Mode: Always stream to indicate how the response was read from cacache
  • X-Local-Cache-Hash: Specific integrity hash for the cached entry
  • X-Local-Cache-Status: One of miss, hit, stale, revalidated, updated, or skip to signal how the response was created
  • X-Local-Cache-Time: UTCString of the cache insertion time for the entry

Using cacache, a call like this may be used to manually fetch the cached entry:

const h = response.headers
cacache.get(h.get('x-local-cache'), h.get('x-local-cache-key'))

// grab content only, directly:
cacache.get.byDigest(h.get('x-local-cache'), h.get('x-local-cache-hash'))
Example
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cachePath: './my-local-cache'
}) // -> 200-level response will be written to disk

> opts.cache

This option follows the standard fetch API cache option. This option will do nothing if opts.cachePath is null. The following values are accepted (as strings):

  • 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.
  • no-store - Fetch behaves as if there is no HTTP cache at all.
  • 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.
  • 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.
  • 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.
  • 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.)

(Note: option descriptions are taken from https://fetch.spec.whatwg.org/#http-network-or-cache-fetch)

Example
const fetch = require('make-fetch-happen').defaults({
  cachePath: './my-cache'
})

// Will error with ENOTCACHED if we haven't already cached this url
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cache: 'only-if-cached'
})

// Will refresh any local content and cache the new response
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cache: 'reload'
})

// Will use any local data, even if stale. Otherwise, will hit network.
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cache: 'force-cache'
})

> opts.cacheAdditionalHeaders

The following headers are always stored in the cache when present:

  • cache-control
  • content-encoding
  • content-language
  • content-type
  • date
  • etag
  • expires
  • last-modified
  • link
  • location
  • pragma
  • vary

This option allows a user to store additional custom headers in the cache.

Example
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cacheAdditionalHeaders: ['my-custom-header'],
})

> opts.proxy

A string or new url.URL()-d URI to proxy through. Different Proxy handlers will be used depending on the proxy's protocol.

Additionally, process.env.HTTP_PROXY, process.env.HTTPS_PROXY, and process.env.PROXY are used if present and no opts.proxy value is provided.

(Pending) process.env.NO_PROXY may also be configured to skip proxying requests for all, or specific domains.

Example
fetch('https://registry.npmjs.org/make-fetch-happen', {
  proxy: 'https://corporate.yourcompany.proxy:4445'
})

fetch('https://registry.npmjs.org/make-fetch-happen', {
  proxy: {
    protocol: 'https:',
    hostname: 'corporate.yourcompany.proxy',
    port: 4445
  }
})

> opts.noProxy

If present, should be a comma-separated string or an array of domain extensions that a proxy should not be used for.

This option may also be provided through process.env.NO_PROXY.

> opts.ca, opts.cert, opts.key, opts.strictSSL

These values are passed in directly to the HTTPS agent and will be used for both proxied and unproxied outgoing HTTPS requests. They mostly correspond to the same options the https module accepts, which will be themselves passed to tls.connect(). opts.strictSSL corresponds to rejectUnauthorized.

> opts.localAddress

Passed directly to http and https request calls. Determines the local address to bind to.

> opts.maxSockets

Default: 15

Maximum number of active concurrent sockets to use for the underlying Http/Https/Proxy agents. This setting applies once per spawned agent.

15 is probably a pretty good value for most use-cases, and balances speed with, uh, not knocking out people's routers. 🤓

> opts.retry

An object that can be used to tune request retry settings. Retries will only be attempted on the following conditions:

  • Request method is NOT POST AND
  • Request status is one of: 408, 420, 429, or any status in the 500-range. OR
  • Request errored with ECONNRESET, ECONNREFUSED, EADDRINUSE, ETIMEDOUT, or the fetch error request-timeout.

The following are worth noting as explicitly not retried:

  • 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.

If opts.retry is false, it is equivalent to {retries: 0}

If opts.retry is a number, it is equivalent to {retries: num}

The following retry options are available if you want more control over it:

  • retries
  • factor
  • minTimeout
  • maxTimeout
  • randomize

For details on what each of these do, refer to the retry documentation.

Example
fetch('https://flaky.site.com', {
  retry: {
    retries: 10,
    randomize: true
  }
})

fetch('http://reliable.site.com', {
  retry: false
})

fetch('http://one-more.site.com', {
  retry: 3
})

> opts.onRetry

A function called with the response or error which caused the retry whenever one is attempted.

Example
fetch('https://flaky.site.com', {
  onRetry(cause) {
    console.log('we will retry because of', cause)
  }
})

> opts.integrity

Matches the response body against the given Subresource Integrity metadata. If verification fails, the request will fail with an EINTEGRITY error.

integrity may either be a string or an ssri Integrity-like.

Example
fetch('https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-1.0.0.tgz', {
  integrity: 'sha1-o47j7zAYnedYFn1dF/fR9OV3z8Q='
}) // -> ok

fetch('https://malicious-registry.org/make-fetch-happen/-/make-fetch-happen-1.0.0.tgz', {
  integrity: 'sha1-o47j7zAYnedYFn1dF/fR9OV3z8Q='
}) // Error: EINTEGRITY

changelog

Changelog

14.0.3 (2024-10-21)

Bug Fixes

  • 3e0fe87 #316 stop ignoring NODE_TLS_REJECT_UNAUTHORIZED when strictSSL is not defined (#316) (@brunoargolo, Bruno Oliveira)

    Dependencies

  • 05fbcc3 #327 bump negotiator from 0.6.4 to 1.0.0 (#327) (@dependabot[bot])

14.0.2 (2024-10-16)

Bug Fixes

  • fa5f233 #324 don't use the request signal in the agent (#324) (@thewilkybarkid, @wraithgar)

    Chores

  • b3742c5 #323 bump @npmcli/template-oss from 4.23.3 to 4.23.4 (#323) (@dependabot[bot], @npm-cli-bot)

14.0.1 (2024-10-02)

Dependencies

14.0.0 (2024-09-26)

⚠️ BREAKING CHANGES

  • make-fetch-happen now supports node ^18.17.0 || >=20.5.0

    Bug Fixes

  • a1beba7 #318 align to npm 10 node engine range (@reggi)

    Dependencies

  • aa5d07a #318 ssri@12.0.0
  • 0113d1f #318 proc-log@5.0.0
  • f0db136 #318 minipass-fetch@4.0.0
  • be3558d #318 @npmcli/agent@3.0.0
  • d255fcb #299 remove is-lambda dependency (#299)

    Chores

  • 30ee575 #318 run template-oss-apply (@reggi)
  • 253f3b9 #309 bump @npmcli/eslint-config from 4.0.5 to 5.0.0 (@dependabot[bot])
  • 58dc7ef #295 bump @npmcli/template-oss to 4.22.0 (@lukekarrys)
  • f51f1de #311 postinstall for dependabot template-oss PR (@hashtagchris)
  • 381750e #311 bump @npmcli/template-oss from 4.23.1 to 4.23.3 (@dependabot[bot])

13.0.1 (2024-04-30)

Bug Fixes

  • 66018e3 log errors on retry (@wraithgar)
  • ed73ef5 #288 always catch and emit cache write errors in promise (#288) (@lukekarrys)

Chores

  • 9e1329c #292 fix linting in tests (@lukekarrys)
  • 4756bda #292 postinstall for dependabot template-oss PR (@lukekarrys)
  • 91df666 #292 bump @npmcli/template-oss from 4.21.3 to 4.21.4 (@dependabot[bot])

13.0.0 (2023-08-15)

⚠️ BREAKING CHANGES

  • support for node <=16.13 has been removed

Bug Fixes

Dependencies

12.0.0 (2023-07-27)

⚠️ BREAKING CHANGES

  • support for node 14 has been removed
  • this changes the underlying http agents to those provided by @npmcli/agent. Backwards compatibility should be fully implemented but due to the scope of this change it was made a breaking change out of an abundance of caution.

Features

Bug Fixes

Documentation

Dependencies

11.1.1 (2023-04-27)

Dependencies

  • b04e3c2 #220 bump minipass from 4.2.7 to 5.0.0 (#220)

11.1.0 (2023-04-13)

Features

  • cca9da0 #225 add support for caching additional headers (#225) (@nlf)

11.0.3 (2023-02-02)

Dependencies

11.0.2 (2022-12-07)

Dependencies

11.0.1 (2022-10-17)

Dependencies

11.0.0 (2022-10-13)

⚠️ BREAKING CHANGES

  • this module no longer attempts to change file ownership automatically
  • make-fetch-happen is now compatible with the following semver range for node: ^14.17.0 || ^16.13.0 || >=18.0.0

Features

  • c293053 #177 postinstall for dependabot template-oss PR (@lukekarrys)

Documentation

  • d63de44 #173 document cause argument to onRetry (#173) (@jmpage)

Dependencies

  • 33d972a #184 bump cacache from 16.1.3 to 17.0.0 (#184)

10.2.1 (2022-08-15)

Bug Fixes

10.2.0 (2022-07-19)

Features

10.1.8 (2022-06-20)

Bug Fixes

  • TypeError: SocksProxyAgent is not a constructor (#161) (4ae4864)

10.1.7 (2022-06-01)

Bug Fixes

Dependencies

  • bump socks-proxy-agent from 6.2.1 to 7.0.0 (#158) (63ed403)

10.1.6 (2022-05-27)

Bug Fixes

  • respect given algorithms instead of always using sha512 (#156) (9baa806)

10.1.5 (2022-05-19)

Bug Fixes

  • cache integrity and size events so late listeners still get them (#154) (8c78584)

10.1.4 (2022-05-18)

Bug Fixes

  • docs: remove reference to unsupported feature (#153) (1d454f1), closes #147
  • pass expected integrity to cacache (a88213e)
  • pass integrityEmitter to cacache to avoid a redundant integrity stream (ae62c21)
  • remove in-memory buffering in favor of full time streaming (ec2db21)

10.1.3 (2022-05-09)

Bug Fixes

  • make defaults chaining actually work (#144) (aa71e81)

10.1.2 (2022-04-05)

Dependencies

10.1.1 (2022-03-29)

Bug Fixes

Documentation

  • remove mention of custom cache provider (#136) (a7f1b55)

10.1.0 (2022-03-24)

Features

Dependencies

  • update cacache requirement from ^16.0.0 to ^16.0.1 (#122) (cb3873c)
  • update cacache requirement from ^16.0.1 to ^16.0.2 (#127) (44fe6ce)
  • update lru-cache requirement from ^7.5.1 to ^7.7.1 (#128) (eb6e7b6)

10.0.6 (2022-03-14)

Dependencies

  • bump cacache from 15.3.0 to 16.0.0 (#121) (de032e9)
  • update lru-cache requirement from ^7.4.1 to ^7.4.2 (#115) (a3f4ba9)
  • update lru-cache requirement from ^7.4.2 to ^7.4.4 (#117) (24a7ddd)
  • update lru-cache requirement from ^7.4.4 to ^7.5.0 (#119) (5ef3bb3)
  • update lru-cache requirement from ^7.5.0 to ^7.5.1 (#120) (8c5db07)
  • update minipass-fetch requirement from ^2.0.2 to ^2.0.3 (#114) (bc71014)

10.0.5 (2022-03-07)

Bug Fixes

  • add code property to unsupported proxy url error (#112) (569a613)

Dependencies

  • update lru-cache requirement from ^7.4.0 to ^7.4.1 (#113) (b7f3e28)
  • update minipass-fetch requirement from ^2.0.1 to ^2.0.2 (#109) (4a9892a)

10.0.4 (2022-03-02)

Dependencies

  • bump minipass-fetch from 1.4.1 to 2.0.1 (#108) (0257b63)
  • update agentkeepalive requirement from ^4.2.0 to ^4.2.1 (#102) (0252efc)
  • update lru-cache requirement from ^7.3.1 to ^7.4.0 (#103) (140ff64)

10.0.3 (2022-02-15)

Bug Fixes

  • set agentkeepalive freeSocketTimeout back to 15 seconds (#100) (3371abf)

10.0.2 (2022-02-10)

Dependencies

  • update lru-cache requirement from ^7.3.0 to ^7.3.1 (6ca02ad)

10.0.1 (2022-02-09)

Bug Fixes

  • agent: don't use polynomial regex (61856c6)

Dependencies

  • bump lru-cache from 6.0.0 to 7.0.1 (3e353d2)
  • update agentkeepalive requirement from ^4.1.3 to ^4.2.0 (ed7f983)
  • update cacache requirement from ^15.2.0 to ^15.3.0 (46e0ac4)
  • update lru-cache requirement from ^7.0.1 to ^7.3.0 (e825c2c)
  • update minipass requirement from ^3.1.3 to ^3.1.6 (778c46a)
  • update minipass-fetch requirement from ^1.3.2 to ^1.4.1 (6fabf4c)
  • update socks-proxy-agent requirement from ^6.0.0 to ^6.1.1 (58f3b29)
  • update ssri requirement from ^8.0.0 to ^8.0.1 (5b75b08)

10.0.0 (2022-01-25)

⚠ BREAKING CHANGES

  • this drops support for node10 and non-LTS versions of node12 and node14

Bug Fixes

  • Add year to license (#68) (d0d86eb)
  • compress option and accept/content encoding header edge cases (#65) (f7d1255)
  • move to template-oss (105872f)
  • revert negotiator preload hack (8688f09)
  • strip cookie header on redirect across hostnames (#71) (ec53f27)
  • Update inline license to use @license comment (#67) (f602e06)

dependencies