Do not use NODE_TLS_REJECT_UNAUTHORIZED anymore. There's a better way in trusting private certificate authorities in node.js.

Self signed certificates shouldn't be such a problem anymore because of free available trusted certificate authorities like Let's Encrypt for example. But if you live in a corporate world, internal certificate authorities are still a thing.

When you try to consume these internal or external services over TLS you might encounter error messages like SELF_SIGNED_CERT_IN_CHAIN. The problem is that the custom CA of your company is not in the list of trusted root certificates. Which is exactly how it should work.

If you are unfamiliar with these kind of errors you would google node.js error SELF_SIGNED_CERT_IN_CHAIN  and most of the search results would suggest to set the environment variable NODE_TLS_REJECT_UNAUTHORIZED to 0 which basically disables the whole certificate validation and is the worst you can do. It's like wearing a blindfold at 200 km/h on the Autobahn, bad idea.

The better way to achieve a secure communication is to get the public certificate (or chain of certificates) of the CA and make them available for node. You can do this either by passing the CA directly to the request:

const { get } = require('https')
const { readFileSync } = require('fs')
const { join } = require('path')

const caCertificates = readFileSync(join(__dirname, 'ca-bundle.pem'))

  host: '',
  port: 8043,
  path: '/',
  ca: caCertificates
}, response => response.pipe(process.stdout)).on('error', console.error)

Or even smarter  to use the environment variable NODE_EXTRA_CA_CERTS introduced in node.js 7.3. This one allows you to specify a file which contains one ore more CA certificates which are automatically added to nodes internal list of trusted certificates.

Most of the articles I found online stopped by telling that there is this new environment variable but did not show any example on how to actually test that it's working (which is actually not that easy if you are not familiar with OpenSSL).

That's why I did the googling and found the great OpenSSL examples by AJ ONeal. I modified it a bit to use that environment variable and put it on Github: Respect mah authoritah