{
  "type": "module",
  "source": "doc/api/api-connector.md",
  "modules": [
    {
      "textRaw": "Connector",
      "name": "connector",
      "introduced_in": "v4.3.0",
      "type": "module",
      "stability": 2,
      "stabilityText": "Stable",
      "desc": "<p>undici opens the underlying socket for every request through a <em>connector</em>. By\ndefault this is handled internally, so most applications never interact with the\nconnector directly. When a request needs additional control over the socket —\nfor example to inspect a TLS certificate, pin a CA fingerprint, or tunnel the\nconnection — a custom connector can be supplied through the <code>connect</code> option of\na <a href=\"Dispatcher.html#class-dispatcher\"><code>Dispatcher</code></a>.</p>\n<p>Use the <code>buildConnector</code> helper to construct a connector with sensible defaults\nand then wrap it:</p>\n<pre><code class=\"language-mjs\">import { buildConnector } from 'undici'\n\nconst connector = buildConnector({ rejectUnauthorized: false })\n</code></pre>\n<p><code>buildConnector</code> accepts the same TLS options as\n<a href=\"https://nodejs.org/api/tls.html#tlsconnectoptions-callback\"><code>tls.connect()</code></a> in addition to the undici-specific options listed\nbelow, and returns a <a href=\"#connectoroptions-callback\"><code>connector</code></a> function that\nundici invokes for each new connection.</p>",
      "methods": [
        {
          "textRaw": "`buildConnector([options])`",
          "name": "buildConnector",
          "type": "method",
          "meta": {
            "added": [
              "v5.23.4"
            ],
            "changes": []
          },
          "signatures": [
            {
              "params": [
                {
                  "textRaw": "`options` {buildConnector.BuildOptions} (optional) Connection options. In addition to every `tls.connect()` option, the following fields are supported:",
                  "name": "options",
                  "type": "buildConnector.BuildOptions",
                  "desc": "(optional) Connection options. In addition to every `tls.connect()` option, the following fields are supported:",
                  "options": [
                    {
                      "textRaw": "`allowH2` {boolean} Whether to offer HTTP/2 (`h2`) during TLS ALPN negotiation. **Default:** `true`.",
                      "name": "allowH2",
                      "type": "boolean",
                      "default": "`true`",
                      "desc": "Whether to offer HTTP/2 (`h2`) during TLS ALPN negotiation."
                    },
                    {
                      "textRaw": "`preferH2` {boolean} Only effective together with `allowH2`. When `true`, ALPN is offered as `['h2', 'http/1.1']` (HTTP/2 first) instead of the default `['http/1.1', 'h2']`. Use this when the server selects the ALPN protocol by _client_ preference (for example, some load balancers) so that HTTP/2 is negotiated whenever the server supports it. If the server does not support HTTP/2, ALPN transparently falls back to `http/1.1`. **Default:** `false`.",
                      "name": "preferH2",
                      "type": "boolean",
                      "default": "`false`",
                      "desc": "Only effective together with `allowH2`. When `true`, ALPN is offered as `['h2', 'http/1.1']` (HTTP/2 first) instead of the default `['http/1.1', 'h2']`. Use this when the server selects the ALPN protocol by _client_ preference (for example, some load balancers) so that HTTP/2 is negotiated whenever the server supports it. If the server does not support HTTP/2, ALPN transparently falls back to `http/1.1`."
                    },
                    {
                      "textRaw": "`maxCachedSessions` {number|null} Maximum number of TLS sessions to cache for reuse. Use `0` to disable TLS session caching. Must be a non-negative integer. **Default:** `100`.",
                      "name": "maxCachedSessions",
                      "type": "number|null",
                      "default": "`100`",
                      "desc": "Maximum number of TLS sessions to cache for reuse. Use `0` to disable TLS session caching. Must be a non-negative integer."
                    },
                    {
                      "textRaw": "`socketPath` {string|null} An IPC endpoint, either a Unix domain socket or a Windows named pipe. **Default:** `null`.",
                      "name": "socketPath",
                      "type": "string|null",
                      "default": "`null`",
                      "desc": "An IPC endpoint, either a Unix domain socket or a Windows named pipe."
                    },
                    {
                      "textRaw": "`timeout` {number|null} The connection timeout in milliseconds. A `ConnectTimeoutError` is raised when the socket fails to connect within this period. **Default:** `10e3`.",
                      "name": "timeout",
                      "type": "number|null",
                      "default": "`10e3`",
                      "desc": "The connection timeout in milliseconds. A `ConnectTimeoutError` is raised when the socket fails to connect within this period."
                    },
                    {
                      "textRaw": "`port` {number} The port to connect to when one is not provided to the connector. Defaults to `443` for `https:` and `80` otherwise.",
                      "name": "port",
                      "type": "number",
                      "desc": "The port to connect to when one is not provided to the connector. Defaults to `443` for `https:` and `80` otherwise."
                    },
                    {
                      "textRaw": "`keepAlive` {boolean|null} Whether to enable TCP keep-alive on the socket. **Default:** `true`.",
                      "name": "keepAlive",
                      "type": "boolean|null",
                      "default": "`true`",
                      "desc": "Whether to enable TCP keep-alive on the socket."
                    },
                    {
                      "textRaw": "`keepAliveInitialDelay` {number|null} The delay in milliseconds before the first TCP keep-alive probe is sent on an idle socket. **Default:** `60e3`.",
                      "name": "keepAliveInitialDelay",
                      "type": "number|null",
                      "default": "`60e3`",
                      "desc": "The delay in milliseconds before the first TCP keep-alive probe is sent on an idle socket."
                    },
                    {
                      "textRaw": "`typeOfService` {number|null} The IP Type of Service (ToS) value to set on the socket. **Default:** `null`.",
                      "name": "typeOfService",
                      "type": "number|null",
                      "default": "`null`",
                      "desc": "The IP Type of Service (ToS) value to set on the socket."
                    }
                  ],
                  "optional": true
                }
              ],
              "return": {
                "textRaw": "Returns: {buildConnector.connector} A `connector` function bound to the supplied options.",
                "name": "return",
                "type": "buildConnector.connector",
                "desc": "A `connector` function bound to the supplied options."
              }
            }
          ],
          "desc": "<p>Builds a connector function. <code>maxCachedSessions</code> must be a non-negative integer\nor an <a href=\"Errors.html#class-invalidargumenterror\"><code>InvalidArgumentError</code></a> is thrown.</p>\n<p>The returned function may be passed directly as the <code>connect</code> option of a\n<a href=\"Dispatcher.html#class-dispatcher\"><code>Dispatcher</code></a>, or wrapped to perform extra validation on each socket before it\nis handed back to undici.</p>\n<pre><code class=\"language-mjs\">import { Client, buildConnector } from 'undici'\n\nconst connector = buildConnector({ rejectUnauthorized: false })\n\nconst client = new Client('https://localhost:3000', {\n  connect (opts, cb) {\n    connector(opts, (err, socket) => {\n      if (err) {\n        cb(err)\n      } else if (/* assertion */ false) {\n        socket.destroy()\n        cb(new Error('kaboom'))\n      } else {\n        cb(null, socket)\n      }\n    })\n  }\n})\n</code></pre>"
        },
        {
          "textRaw": "`connector(options, callback)`",
          "name": "connector",
          "type": "method",
          "meta": {
            "added": [
              "v4.3.0"
            ],
            "changes": []
          },
          "signatures": [
            {
              "params": [
                {
                  "textRaw": "`options` {Object} Per-connection options provided by undici.",
                  "name": "options",
                  "type": "Object",
                  "desc": "Per-connection options provided by undici.",
                  "options": [
                    {
                      "textRaw": "`hostname` {string} The host to connect to.",
                      "name": "hostname",
                      "type": "string",
                      "desc": "The host to connect to."
                    },
                    {
                      "textRaw": "`host` {string} (optional) The value of the request `Host` header, used to derive the TLS `servername` when one is not supplied.",
                      "name": "host",
                      "type": "string",
                      "desc": "(optional) The value of the request `Host` header, used to derive the TLS `servername` when one is not supplied."
                    },
                    {
                      "textRaw": "`protocol` {string} The request protocol, for example `'https:'` or `'http:'`. A value of `'https:'` establishes a TLS connection.",
                      "name": "protocol",
                      "type": "string",
                      "desc": "The request protocol, for example `'https:'` or `'http:'`. A value of `'https:'` establishes a TLS connection."
                    },
                    {
                      "textRaw": "`port` {string} The port to connect to. Defaults to `443` for `https:` and `80` otherwise.",
                      "name": "port",
                      "type": "string",
                      "desc": "The port to connect to. Defaults to `443` for `https:` and `80` otherwise."
                    },
                    {
                      "textRaw": "`servername` {string} (optional) The TLS Server Name Indication (SNI) value. Derived from `host` when omitted.",
                      "name": "servername",
                      "type": "string",
                      "desc": "(optional) The TLS Server Name Indication (SNI) value. Derived from `host` when omitted."
                    },
                    {
                      "textRaw": "`localAddress` {string|null} (optional) The local address the socket should connect from.",
                      "name": "localAddress",
                      "type": "string|null",
                      "desc": "(optional) The local address the socket should connect from."
                    },
                    {
                      "textRaw": "`httpSocket` {Socket} (optional) An existing socket on which to establish the secure connection rather than creating a new one. May only be supplied for a TLS upgrade (`protocol` of `'https:'`).",
                      "name": "httpSocket",
                      "type": "Socket",
                      "desc": "(optional) An existing socket on which to establish the secure connection rather than creating a new one. May only be supplied for a TLS upgrade (`protocol` of `'https:'`)."
                    }
                  ]
                },
                {
                  "textRaw": "`callback` {Function} Called once the socket has connected or failed.",
                  "name": "callback",
                  "type": "Function",
                  "desc": "Called once the socket has connected or failed.",
                  "options": [
                    {
                      "textRaw": "`err` {Error|null} The connection error, or `null` on success.",
                      "name": "err",
                      "type": "Error|null",
                      "desc": "The connection error, or `null` on success."
                    },
                    {
                      "textRaw": "`socket` {Socket|TLSSocket|null} The connected socket, or `null` on failure.",
                      "name": "socket",
                      "type": "Socket|TLSSocket|null",
                      "desc": "The connected socket, or `null` on failure."
                    }
                  ]
                }
              ],
              "return": {
                "textRaw": "Returns: {Socket|TLSSocket} The socket being established.",
                "name": "return",
                "type": "Socket|TLSSocket",
                "desc": "The socket being established."
              }
            }
          ],
          "desc": "<p>The function returned by <a href=\"#buildconnectoroptions\"><code>buildConnector()</code></a>. undici\ncalls it for every new connection. It opens a <a href=\"https://nodejs.org/api/net.html#class-netsocket\"><code>net.Socket</code></a> for <code>http:</code>\ntargets or a <a href=\"https://nodejs.org/api/tls.html#class-tlstlssocket\"><code>tls.TLSSocket</code></a> for <code>https:</code> targets, applies TCP keep-alive and\nthe connect timeout, and invokes <code>callback</code> once the socket connects or errors.\nThe socket is also returned synchronously.</p>\n<p>When connecting over TLS, established sessions are cached (subject to\n<code>maxCachedSessions</code>) and reused for subsequent connections to the same\n<code>servername</code> or <code>hostname</code>.</p>",
          "modules": [
            {
              "textRaw": "Example: validate the CA fingerprint",
              "name": "example:_validate_the_ca_fingerprint",
              "type": "module",
              "desc": "<p>A custom connector is a convenient place to verify the server certificate before\nany request is sent over the socket.</p>\n<pre><code class=\"language-mjs\">import { Client, buildConnector } from 'undici'\n\nconst caFingerprint = 'FO:OB:AR'\nconst connector = buildConnector({ rejectUnauthorized: false })\n\nconst client = new Client('https://localhost:3000', {\n  connect (opts, cb) {\n    connector(opts, (err, socket) => {\n      if (err) {\n        cb(err)\n      } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) {\n        socket.destroy()\n        cb(new Error('Fingerprint does not match or malformed certificate'))\n      } else {\n        cb(null, socket)\n      }\n    })\n  }\n})\n\nclient.request({\n  path: '/',\n  method: 'GET'\n}, (err, data) => {\n  if (err) throw err\n\n  const bufs = []\n  data.body.on('data', (buf) => {\n    bufs.push(buf)\n  })\n  data.body.on('end', () => {\n    console.log(Buffer.concat(bufs).toString('utf8'))\n    client.close()\n  })\n})\n\nfunction getIssuerCertificate (socket) {\n  let certificate = socket.getPeerCertificate(true)\n  while (certificate &#x26;&#x26; Object.keys(certificate).length > 0) {\n    // Invalid certificate.\n    if (certificate.issuerCertificate == null) {\n      return null\n    }\n\n    // We have reached the root certificate. In case of self-signed\n    // certificates, `issuerCertificate` may be a circular reference.\n    if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) {\n      break\n    }\n\n    certificate = certificate.issuerCertificate\n  }\n  return certificate\n}\n</code></pre>",
              "displayName": "Example: validate the CA fingerprint"
            }
          ]
        }
      ]
    }
  ]
}