DEV Community

Cover image for How to use a proxy in a nodejs environment
Adam
Adam

Posted on • Originally published at urbanisierung.dev

2

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:

  • https_proxy: Proxy for https traffic
  • http_proxy: Proxy for http traffic
  • no_proxy: URLs that should not run via a 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:

import { EnvHttpProxyAgent } from "undici";

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

await fetch("https://...", {
  ...proxyAgent,
});
Enter fullscreen mode Exit fullscreen mode

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.

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay