logo

How to use a proxy in a nodejs environment

How to use a proxy in a nodejs environment

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

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:

import { EnvHttpProxyAgent } from "undici";

const ENV_HTTP_PROXY_AGENT = new EnvHttpProxyAgent();
const proxyAgent = { dispatcher: ENV_HTTP_PROXY_AGENT } as any;

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.

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

newsletter
Published on 2024-12-08, last updated on 2024-12-16 by Adam
Comments or questions? Open a new discussion on github.
Adam Urban

Adam Urban is fullstack engineer, loves serverless and generative art, and is building side projects like weeklyfoo.com, flethy.com and diypunks.xyz in his free time.