Adding trusted CA to node client with axios

Giacomo Mariani
1 min readMay 16, 2019

I had to create a node client which sends a get request with some parameters to a server. The server is using a self signed certificate, so I had to add the CA as trusted on the client side. Here is my solution creating an httpsAgent and using axios. I saved the CA certificate in the project root and named it ca.crt

const https = require('https');
const fs = require('fs');
const axios = require('axios');
const url = 'https://serverurl.com';
let caCrt = '';
try {
caCrt = fs.readFileSync('./ca.crt')
} catch(err) {
console.log('Make sure that the CA cert file is named ca.crt', err);
}
const httpsAgent = new https.Agent({ ca: caCrt, keepAlive: false });
const sendGetReq = (params) => {
axios.get(url, {
params: params,
httpsAgent: httpsAgent
})
.then( res => {
console.log(Date());
console.log('statusCode', res.status);
console.log('Response', res.data);
}).catch( error => console.log(`${Date()} fail: ${url}: ${error}`));
};

If this tutorial helped you, you can thank me by buying me coffee.

--

--