From dfe56d3aa260c17f9b58d992131bd0be2d477bc1 Mon Sep 17 00:00:00 2001 From: Ali BARIN Date: Mon, 13 May 2024 09:14:06 +0000 Subject: [PATCH] feat: add no_proxy support in http(s) agents --- .../backend/src/helpers/axios-with-proxy.js | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/backend/src/helpers/axios-with-proxy.js b/packages/backend/src/helpers/axios-with-proxy.js index e355573f..0dbad80a 100644 --- a/packages/backend/src/helpers/axios-with-proxy.js +++ b/packages/backend/src/helpers/axios-with-proxy.js @@ -6,14 +6,16 @@ const config = axios.defaults; const httpProxyUrl = process.env.http_proxy; const httpsProxyUrl = process.env.https_proxy; const supportsProxy = httpProxyUrl || httpsProxyUrl; +const noProxyEnv = process.env.no_proxy; +const noProxyHosts = noProxyEnv ? noProxyEnv.split(',').map(host => host.trim()) : []; if (supportsProxy) { if (httpProxyUrl) { - config.httpAgent = new HttpProxyAgent(process.env.http_proxy); + config.httpAgent = new HttpProxyAgent(httpProxyUrl); } if (httpsProxyUrl) { - config.httpsAgent = new HttpsProxyAgent(process.env.https_proxy); + config.httpsAgent = new HttpsProxyAgent(httpsProxyUrl); } config.proxy = false; @@ -21,4 +23,21 @@ if (supportsProxy) { const axiosWithProxyInstance = axios.create(config); +function shouldSkipProxy(hostname) { + return noProxyHosts.some(noProxyHost => { + return hostname.endsWith(noProxyHost) || hostname === noProxyHost; + }); +}; + +axiosWithProxyInstance.interceptors.request.use(function skipProxyIfInNoProxy(requestConfig) { + const hostname = new URL(requestConfig.url).hostname; + + if (supportsProxy && shouldSkipProxy(hostname)) { + requestConfig.httpAgent = undefined; + requestConfig.httpsAgent = undefined; + } + + return requestConfig; +}); + export default axiosWithProxyInstance;