Tomáš Zato
Tomáš Zato

Reputation: 53255

How to selectively allow self-signed certificates when using built-in Node.js fetch()?

With node-fetch or https module directly, you can specify that unauthorized HTTPS requests should not be rejected. For example:

const fetch = require('node-fetch');
const https = require('https');

const httpsAgent = new https.Agent({
      rejectUnauthorized: false,
    });

const response = await fetch(url, {
      method: 'POST',
      headers: headers,
      body: body,
      agent: httpsAgent,
    });

However what if I use fetch that is already built in in Node.js? I don't see any documentation about any special "non-browser" arguments. I don't want to globally disable HTTPS verification, only for the requests I am making while testing a particular endpoint.

I tried just passing agent like with node-fetch, but unsurprisingly, that does not work:

const httpsAgent = new https.Agent({
    rejectUnauthorized: false,
});
const request = await fetch("https://my_test_api.local/test", {
    method: "GET",
    agent: httpsAgent
});

Result:

TypeError: fetch failed
    at node:internal/deps/undici/undici:13178:13
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///home/me/myproject/apitest.js:60:25 {
  [cause]: Error: self-signed certificate
      at TLSSocket.onConnectSecure (node:_tls_wrap:1676:34)
      at TLSSocket.emit (node:events:520:28)
      at TLSSocket._finishInit (node:_tls_wrap:1087:8)
      at ssl.onhandshakedone (node:_tls_wrap:873:12) {
    code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
  }
}

Also, it is kinda weird that fetch here throws a TypeError, but that's beside the point.

Upvotes: 1

Views: 112

Answers (1)

pmoleri
pmoleri

Reputation: 4451

You can use the environment variable NODE_EXTRA_CA_CERTS to pass a certificates file.

node --help
...
Environment variables:
...
NODE_EXTRA_CA_CERTS           path to additional CA certificates file. Only read
                              once during process startup.

e.g. NODE_EXTRA_CA_CERTS=my-custom-ca.pem

Upvotes: 1

Related Questions