←
~/blog/how-to-use-a-proxy-in-a-nodejs-environment
04/23

How to use a proxy in a nodejs environment

2024-12-08newsletter
read post⏎

There is an established standard by which proxies are configured. It runs via the following environment variables:

  • https_proxy: Proxy for https traffic
  • http_proxy: Proxy for http traffic
  • no_proxy: URLs that should not run via a proxy.
https_proxy
http_proxy
no_proxy

The native fetch client of NodeJS does not offer any functionality for this out-of-the-box, but there is an agent from the undici http client that you can use:

fetch
undici
import { EnvHttpProxyAgent } from "undici"; 
const ENV_HTTP_PROXY_AGENT = new EnvHttpProxyAgent(); 
const proxyAgent = { dispatcher: ENV_HTTP_PROXY_AGENT }; 
await fetch("https://...", { ...proxyAgent, });

The node type definition does not support a dispatcher attribute for fetch, but it’s a supported logic. So if you’re using TypeScript you can ignore the error or use the beloved as any pattern for the proxy agent.

const proxyAgent = { dispatcher: ENV_HTTP_PROXY_AGENT } as any;

And that’s everything, no manual evaluation of the environment variables. Everything is handled by the EnvHttpProxyAgent from undici.

EnvHttpProxyAgent
undici