11cb0ef41Sopenharmony_ci# Class: Client
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciExtends: `undici.Dispatcher`
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ciA basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciRequests are not guaranteed to be dispatched in order of invocation.
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ci## `new Client(url[, options])`
101cb0ef41Sopenharmony_ci
111cb0ef41Sopenharmony_ciArguments:
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ci* **url** `URL | string` - Should only include the **protocol, hostname, and port**.
141cb0ef41Sopenharmony_ci* **options** `ClientOptions` (optional)
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_ciReturns: `Client`
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_ci### Parameter: `ClientOptions`
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_ci> ⚠️ Warning: The `H2` support is experimental.
211cb0ef41Sopenharmony_ci
221cb0ef41Sopenharmony_ci* **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds.
231cb0ef41Sopenharmony_ci* **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds.
241cb0ef41Sopenharmony_ci* **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Defaults to 10 minutes.
251cb0ef41Sopenharmony_ci* **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds.
261cb0ef41Sopenharmony_ci* **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `1e3` - A number of milliseconds subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 1 second.
271cb0ef41Sopenharmony_ci* **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB.
281cb0ef41Sopenharmony_ci* **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable.
291cb0ef41Sopenharmony_ci* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections.
301cb0ef41Sopenharmony_ci* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`.
311cb0ef41Sopenharmony_ci* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body.
321cb0ef41Sopenharmony_ci* **interceptors** `{ Client: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time.
331cb0ef41Sopenharmony_ci* **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version.
341cb0ef41Sopenharmony_ci* **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details.
351cb0ef41Sopenharmony_ci* **allowH2**: `boolean` - Default: `false`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation.
361cb0ef41Sopenharmony_ci* **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
371cb0ef41Sopenharmony_ci
381cb0ef41Sopenharmony_ci#### Parameter: `ConnectOptions`
391cb0ef41Sopenharmony_ci
401cb0ef41Sopenharmony_ciEvery Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
411cb0ef41Sopenharmony_ciFurthermore, the following options can be passed:
421cb0ef41Sopenharmony_ci
431cb0ef41Sopenharmony_ci* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe.
441cb0ef41Sopenharmony_ci* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100.
451cb0ef41Sopenharmony_ci* **timeout** `number | null` (optional) -  In milliseconds, Default `10e3`.
461cb0ef41Sopenharmony_ci* **servername** `string | null` (optional)
471cb0ef41Sopenharmony_ci* **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled
481cb0ef41Sopenharmony_ci* **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds
491cb0ef41Sopenharmony_ci
501cb0ef41Sopenharmony_ci### Example - Basic Client instantiation
511cb0ef41Sopenharmony_ci
521cb0ef41Sopenharmony_ciThis will instantiate the undici Client, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`.
531cb0ef41Sopenharmony_ci
541cb0ef41Sopenharmony_ci```js
551cb0ef41Sopenharmony_ci'use strict'
561cb0ef41Sopenharmony_ciimport { Client } from 'undici'
571cb0ef41Sopenharmony_ci
581cb0ef41Sopenharmony_ciconst client = new Client('http://localhost:3000')
591cb0ef41Sopenharmony_ci```
601cb0ef41Sopenharmony_ci
611cb0ef41Sopenharmony_ci### Example - Custom connector
621cb0ef41Sopenharmony_ci
631cb0ef41Sopenharmony_ciThis will allow you to perform some additional check on the socket that will be used for the next request.
641cb0ef41Sopenharmony_ci
651cb0ef41Sopenharmony_ci```js
661cb0ef41Sopenharmony_ci'use strict'
671cb0ef41Sopenharmony_ciimport { Client, buildConnector } from 'undici'
681cb0ef41Sopenharmony_ci
691cb0ef41Sopenharmony_ciconst connector = buildConnector({ rejectUnauthorized: false })
701cb0ef41Sopenharmony_ciconst client = new Client('https://localhost:3000', {
711cb0ef41Sopenharmony_ci  connect (opts, cb) {
721cb0ef41Sopenharmony_ci    connector(opts, (err, socket) => {
731cb0ef41Sopenharmony_ci      if (err) {
741cb0ef41Sopenharmony_ci        cb(err)
751cb0ef41Sopenharmony_ci      } else if (/* assertion */) {
761cb0ef41Sopenharmony_ci        socket.destroy()
771cb0ef41Sopenharmony_ci        cb(new Error('kaboom'))
781cb0ef41Sopenharmony_ci      } else {
791cb0ef41Sopenharmony_ci        cb(null, socket)
801cb0ef41Sopenharmony_ci      }
811cb0ef41Sopenharmony_ci    })
821cb0ef41Sopenharmony_ci  }
831cb0ef41Sopenharmony_ci})
841cb0ef41Sopenharmony_ci```
851cb0ef41Sopenharmony_ci
861cb0ef41Sopenharmony_ci## Instance Methods
871cb0ef41Sopenharmony_ci
881cb0ef41Sopenharmony_ci### `Client.close([callback])`
891cb0ef41Sopenharmony_ci
901cb0ef41Sopenharmony_ciImplements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise).
911cb0ef41Sopenharmony_ci
921cb0ef41Sopenharmony_ci### `Client.destroy([error, callback])`
931cb0ef41Sopenharmony_ci
941cb0ef41Sopenharmony_ciImplements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise).
951cb0ef41Sopenharmony_ci
961cb0ef41Sopenharmony_ciWaits until socket is closed before invoking the callback (or returning a promise if no callback is provided).
971cb0ef41Sopenharmony_ci
981cb0ef41Sopenharmony_ci### `Client.connect(options[, callback])`
991cb0ef41Sopenharmony_ci
1001cb0ef41Sopenharmony_ciSee [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback).
1011cb0ef41Sopenharmony_ci
1021cb0ef41Sopenharmony_ci### `Client.dispatch(options, handlers)`
1031cb0ef41Sopenharmony_ci
1041cb0ef41Sopenharmony_ciImplements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler).
1051cb0ef41Sopenharmony_ci
1061cb0ef41Sopenharmony_ci### `Client.pipeline(options, handler)`
1071cb0ef41Sopenharmony_ci
1081cb0ef41Sopenharmony_ciSee [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler).
1091cb0ef41Sopenharmony_ci
1101cb0ef41Sopenharmony_ci### `Client.request(options[, callback])`
1111cb0ef41Sopenharmony_ci
1121cb0ef41Sopenharmony_ciSee [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback).
1131cb0ef41Sopenharmony_ci
1141cb0ef41Sopenharmony_ci### `Client.stream(options, factory[, callback])`
1151cb0ef41Sopenharmony_ci
1161cb0ef41Sopenharmony_ciSee [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback).
1171cb0ef41Sopenharmony_ci
1181cb0ef41Sopenharmony_ci### `Client.upgrade(options[, callback])`
1191cb0ef41Sopenharmony_ci
1201cb0ef41Sopenharmony_ciSee [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback).
1211cb0ef41Sopenharmony_ci
1221cb0ef41Sopenharmony_ci## Instance Properties
1231cb0ef41Sopenharmony_ci
1241cb0ef41Sopenharmony_ci### `Client.closed`
1251cb0ef41Sopenharmony_ci
1261cb0ef41Sopenharmony_ci* `boolean`
1271cb0ef41Sopenharmony_ci
1281cb0ef41Sopenharmony_ci`true` after `client.close()` has been called.
1291cb0ef41Sopenharmony_ci
1301cb0ef41Sopenharmony_ci### `Client.destroyed`
1311cb0ef41Sopenharmony_ci
1321cb0ef41Sopenharmony_ci* `boolean`
1331cb0ef41Sopenharmony_ci
1341cb0ef41Sopenharmony_ci`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed.
1351cb0ef41Sopenharmony_ci
1361cb0ef41Sopenharmony_ci### `Client.pipelining`
1371cb0ef41Sopenharmony_ci
1381cb0ef41Sopenharmony_ci* `number`
1391cb0ef41Sopenharmony_ci
1401cb0ef41Sopenharmony_ciProperty to get and set the pipelining factor.
1411cb0ef41Sopenharmony_ci
1421cb0ef41Sopenharmony_ci## Instance Events
1431cb0ef41Sopenharmony_ci
1441cb0ef41Sopenharmony_ci### Event: `'connect'`
1451cb0ef41Sopenharmony_ci
1461cb0ef41Sopenharmony_ciSee [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect).
1471cb0ef41Sopenharmony_ci
1481cb0ef41Sopenharmony_ciParameters:
1491cb0ef41Sopenharmony_ci
1501cb0ef41Sopenharmony_ci* **origin** `URL`
1511cb0ef41Sopenharmony_ci* **targets** `Array<Dispatcher>`
1521cb0ef41Sopenharmony_ci
1531cb0ef41Sopenharmony_ciEmitted when a socket has been created and connected. The client will connect once `client.size > 0`.
1541cb0ef41Sopenharmony_ci
1551cb0ef41Sopenharmony_ci#### Example - Client connect event
1561cb0ef41Sopenharmony_ci
1571cb0ef41Sopenharmony_ci```js
1581cb0ef41Sopenharmony_ciimport { createServer } from 'http'
1591cb0ef41Sopenharmony_ciimport { Client } from 'undici'
1601cb0ef41Sopenharmony_ciimport { once } from 'events'
1611cb0ef41Sopenharmony_ci
1621cb0ef41Sopenharmony_ciconst server = createServer((request, response) => {
1631cb0ef41Sopenharmony_ci  response.end('Hello, World!')
1641cb0ef41Sopenharmony_ci}).listen()
1651cb0ef41Sopenharmony_ci
1661cb0ef41Sopenharmony_ciawait once(server, 'listening')
1671cb0ef41Sopenharmony_ci
1681cb0ef41Sopenharmony_ciconst client = new Client(`http://localhost:${server.address().port}`)
1691cb0ef41Sopenharmony_ci
1701cb0ef41Sopenharmony_ciclient.on('connect', (origin) => {
1711cb0ef41Sopenharmony_ci  console.log(`Connected to ${origin}`) // should print before the request body statement
1721cb0ef41Sopenharmony_ci})
1731cb0ef41Sopenharmony_ci
1741cb0ef41Sopenharmony_citry {
1751cb0ef41Sopenharmony_ci  const { body } = await client.request({
1761cb0ef41Sopenharmony_ci    path: '/',
1771cb0ef41Sopenharmony_ci    method: 'GET'
1781cb0ef41Sopenharmony_ci  })
1791cb0ef41Sopenharmony_ci  body.setEncoding('utf-8')
1801cb0ef41Sopenharmony_ci  body.on('data', console.log)
1811cb0ef41Sopenharmony_ci  client.close()
1821cb0ef41Sopenharmony_ci  server.close()
1831cb0ef41Sopenharmony_ci} catch (error) {
1841cb0ef41Sopenharmony_ci  console.error(error)
1851cb0ef41Sopenharmony_ci  client.close()
1861cb0ef41Sopenharmony_ci  server.close()
1871cb0ef41Sopenharmony_ci}
1881cb0ef41Sopenharmony_ci```
1891cb0ef41Sopenharmony_ci
1901cb0ef41Sopenharmony_ci### Event: `'disconnect'`
1911cb0ef41Sopenharmony_ci
1921cb0ef41Sopenharmony_ciSee [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect).
1931cb0ef41Sopenharmony_ci
1941cb0ef41Sopenharmony_ciParameters:
1951cb0ef41Sopenharmony_ci
1961cb0ef41Sopenharmony_ci* **origin** `URL`
1971cb0ef41Sopenharmony_ci* **targets** `Array<Dispatcher>`
1981cb0ef41Sopenharmony_ci* **error** `Error`
1991cb0ef41Sopenharmony_ci
2001cb0ef41Sopenharmony_ciEmitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`.
2011cb0ef41Sopenharmony_ci
2021cb0ef41Sopenharmony_ci#### Example - Client disconnect event
2031cb0ef41Sopenharmony_ci
2041cb0ef41Sopenharmony_ci```js
2051cb0ef41Sopenharmony_ciimport { createServer } from 'http'
2061cb0ef41Sopenharmony_ciimport { Client } from 'undici'
2071cb0ef41Sopenharmony_ciimport { once } from 'events'
2081cb0ef41Sopenharmony_ci
2091cb0ef41Sopenharmony_ciconst server = createServer((request, response) => {
2101cb0ef41Sopenharmony_ci  response.destroy()
2111cb0ef41Sopenharmony_ci}).listen()
2121cb0ef41Sopenharmony_ci
2131cb0ef41Sopenharmony_ciawait once(server, 'listening')
2141cb0ef41Sopenharmony_ci
2151cb0ef41Sopenharmony_ciconst client = new Client(`http://localhost:${server.address().port}`)
2161cb0ef41Sopenharmony_ci
2171cb0ef41Sopenharmony_ciclient.on('disconnect', (origin) => {
2181cb0ef41Sopenharmony_ci  console.log(`Disconnected from ${origin}`)
2191cb0ef41Sopenharmony_ci})
2201cb0ef41Sopenharmony_ci
2211cb0ef41Sopenharmony_citry {
2221cb0ef41Sopenharmony_ci  await client.request({
2231cb0ef41Sopenharmony_ci    path: '/',
2241cb0ef41Sopenharmony_ci    method: 'GET'
2251cb0ef41Sopenharmony_ci  })
2261cb0ef41Sopenharmony_ci} catch (error) {
2271cb0ef41Sopenharmony_ci  console.error(error.message)
2281cb0ef41Sopenharmony_ci  client.close()
2291cb0ef41Sopenharmony_ci  server.close()
2301cb0ef41Sopenharmony_ci}
2311cb0ef41Sopenharmony_ci```
2321cb0ef41Sopenharmony_ci
2331cb0ef41Sopenharmony_ci### Event: `'drain'`
2341cb0ef41Sopenharmony_ci
2351cb0ef41Sopenharmony_ciEmitted when pipeline is no longer busy.
2361cb0ef41Sopenharmony_ci
2371cb0ef41Sopenharmony_ciSee [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain).
2381cb0ef41Sopenharmony_ci
2391cb0ef41Sopenharmony_ci#### Example - Client drain event
2401cb0ef41Sopenharmony_ci
2411cb0ef41Sopenharmony_ci```js
2421cb0ef41Sopenharmony_ciimport { createServer } from 'http'
2431cb0ef41Sopenharmony_ciimport { Client } from 'undici'
2441cb0ef41Sopenharmony_ciimport { once } from 'events'
2451cb0ef41Sopenharmony_ci
2461cb0ef41Sopenharmony_ciconst server = createServer((request, response) => {
2471cb0ef41Sopenharmony_ci  response.end('Hello, World!')
2481cb0ef41Sopenharmony_ci}).listen()
2491cb0ef41Sopenharmony_ci
2501cb0ef41Sopenharmony_ciawait once(server, 'listening')
2511cb0ef41Sopenharmony_ci
2521cb0ef41Sopenharmony_ciconst client = new Client(`http://localhost:${server.address().port}`)
2531cb0ef41Sopenharmony_ci
2541cb0ef41Sopenharmony_ciclient.on('drain', () => {
2551cb0ef41Sopenharmony_ci  console.log('drain event')
2561cb0ef41Sopenharmony_ci  client.close()
2571cb0ef41Sopenharmony_ci  server.close()
2581cb0ef41Sopenharmony_ci})
2591cb0ef41Sopenharmony_ci
2601cb0ef41Sopenharmony_ciconst requests = [
2611cb0ef41Sopenharmony_ci  client.request({ path: '/', method: 'GET' }),
2621cb0ef41Sopenharmony_ci  client.request({ path: '/', method: 'GET' }),
2631cb0ef41Sopenharmony_ci  client.request({ path: '/', method: 'GET' })
2641cb0ef41Sopenharmony_ci]
2651cb0ef41Sopenharmony_ci
2661cb0ef41Sopenharmony_ciawait Promise.all(requests)
2671cb0ef41Sopenharmony_ci
2681cb0ef41Sopenharmony_ciconsole.log('requests completed')
2691cb0ef41Sopenharmony_ci```
2701cb0ef41Sopenharmony_ci
2711cb0ef41Sopenharmony_ci### Event: `'error'`
2721cb0ef41Sopenharmony_ci
2731cb0ef41Sopenharmony_ciInvoked for users errors such as throwing in the `onError` handler.
274