DEV Community

Tin Castle
Tin Castle

Posted on

Node.js fetch with proxy

§ Install undici:

npm i undici
Enter fullscreen mode Exit fullscreen mode

§ Instantiate an EnvHttpProxyAgent:

const { EnvHttpProxyAgent } 
cosnt proxyAgent = new EnvHttpProxyAgent()
Enter fullscreen mode Exit fullscreen mode

This automatically detect proxy. It works both with and without proxy.

§ Define a function fetch which wraps request of undici:

const fetch = async (url) => request(url, { dispatcher: proxyAgent })
Enter fullscreen mode Exit fullscreen mode

§ Adjust your codebase since this fetch and builtin fetch have the slightly different return types. But it is not difficult.

§ In addition, if your organization use a self-signed certificate, on runtime:

NODE_EXTRA_CA_CERTS=<CA cert file path> node app.js
Enter fullscreen mode Exit fullscreen mode

Top comments (0)