Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a request in native Fetch with Proxy in NodeJS 18

In version 18 of Node JS there is already the possibility of making request Fetch without installing packages (example: Axios).

My question is if you can make a request to this Native Fetch with Proxy without installing packages or do you have to install packages to use a Proxy in Fetch?

In case I have to install a package to use Proxy in Fetch, what would be the best one to use with Node's new Fetch?

I really appreciate it if you can leave an implementation code, thanks!

like image 780
bruxs Avatar asked Sep 12 '25 19:09

bruxs


1 Answers

I got proxies to work with native fetch(), but I did have to install a package (this is because they haven't exposed the functionality to set the proxy nativly, see this issue mentioned in the other answer). This answer might also be useful to those looking to set a proxy server for existing packages that use native fetch() (in my case, Octokit).

I couldn't get it to accept the certificate it presented, as it was signed with an internal Root CA and returned an error Error: self-signed certificate in certificate chain (SELF_SIGNED_CERT_IN_CHAIN). I tried setting the env var NODE_EXTRA_CA_CERTS to a file with the required root CA, to no avail. I also tried specifying {rejectUnauthorized: false} in both the ProxyAgent ctor and the options for the fetch itself, but it didn't have any effect. So I decided to set the env var NODE_TLS_REJECT_UNAUTHORIZED. If anyone knows how to get custom root CAs to work with native fetch() and proxies, please contribute.

After installing the undici NPM package (via npm install undici or yarn add undici), use the following to grab the proxy config from the https_proxy env var:

import { env } from "process";
import { setGlobalDispatcher, ProxyAgent } from "undici";

if (env.https_proxy) {
  // Corporate proxy uses CA not in undici's certificate store
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
  const dispatcher = new ProxyAgent({uri: new URL(env.https_proxy).toString() });
  setGlobalDispatcher(dispatcher);
}

await fetch("https://www.stackoverflow.com");
like image 176
Allon Guralnek Avatar answered Sep 15 '25 09:09

Allon Guralnek