axios with proxy and custom SSL certificate

This article summarizes what made me struggle days.

Fix https-proxy-agent to support CA

It was originally proposed here by maslakov.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { HttpsProxyAgent, HttpsProxyAgentOptions } from 'https-proxy-agent';
import { ClientRequest, RequestOptions } from 'agent-base';
import { Socket } from 'net';

export class PatchedHttpsProxyAgent extends HttpsProxyAgent {
private ca: any;

constructor(opts: HttpsProxyAgentOptions) {
super(opts);
this.ca = opts.ca;
}

async callback(req: ClientRequest, opts: RequestOptions): Promise<Socket> {
return super.callback(req, Object.assign(opts, { ca: this.ca }));
}
}

Working prototype

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const axios = require('axios');
const HttpsProxyAgent = require('https-proxy-agent');
const ca = require('ssl-root-cas/latest').create();

ca.addFile(certificateFilePath);

const httpsAgent = new HttpsProxyAgent({
protocol: 'http',
host: 'proxy_host',
port: 8080,
ca,
});

axios.defaults.httpsAgent = httpsAgent;

References

  1. PatchedHttpsProxyAgent