nodejs - error self signed certificate in certificate chain

You can fix this issue using NODE_TLS_REJECT_UNAUTHORIZED=0 in the terminal or inserting the following line within the JS file.

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

Beware that this a hack and it should not be used in production.

If you are using windows then run the following command in the command prompt:

set NODE_TLS_REJECT_UNAUTHORIZED=0 

After that, npm install <my-package> will work.


Option 1: Disable the warning (useful for dev)

From your question I'm guessing you are doing this in development as you are using a self signed certificate for SSL communication.

If that's the case, add as an environment variable wherever you are running node

export NODE_TLS_REJECT_UNAUTHORIZED='0'
node app.js

or running node directly with

NODE_TLS_REJECT_UNAUTHORIZED='0' node app.js

This instructs Node to allow untrusted certificates (untrusted = not verified by a certificate authority)

If you don't want to set an environment variable or need to do this for multiple applications npm has a strict-ssl config you set to false

npm config set strict-ssl=false

Option 2: Load in CA cert, like postman (useful for testing with TLS)

If you have a CA cert already like the poster @kDoyle mentioned then you can configure in each request (thanks @nic ferrier).

 let opts = {
    method: 'GET',
    hostname: "localhost",
    port: listener.address().port,
    path: '/',
    ca: fs.readFileSync("cacert.pem")
  };

  https.request(opts, (response) => { }).end();

Option 3: Use a proper SSL Cert from a trusted source (useful for production)

letsencrypt.org is free, easy to set up and the keys can be automatically rotated. https://letsencrypt.org/docs/