dedLyv22
dedLyv22

Reputation: 91

node.js 18.3 native fetch request with a proxy

I would like to make a request with a proxy using native fetch node.js 18.3 but i have no idea how.

My code:

import proxyAgent from 'proxy-agent';

(async () => {
    const res = await fetch('https://api.ipify.org?format=json', {
        agent: new proxyAgent('http://80.48.119.28:8080'),
    });
    const data = await res.json();
    console.log(data); //it shows my ip
})();

Upvotes: 9

Views: 4610

Answers (2)

hax
hax

Reputation: 1464

Nodejs fetch APIs use undici which is based on totally different design, proxy-agent package is not compatible with undici, and can only be used with old API like http.request. See issue: https://github.com/TooTallNate/proxy-agents/issues/239 .

Note, undici support proxy, but currently undici's ProxyAgent is not exposed to nodejs directly, so you need to install undici package and import it manually. You can track the issue here: https://github.com/nodejs/node/issues/43187 .

Upvotes: 1

Taha Azzabi
Taha Azzabi

Reputation: 2570

You need to put the agent in the request Headers

import proxyAgent from 'proxy-agent';

(async () => {
    const res = await fetch('https://api.ipify.org?format=json', {
      headers: {
        agent: new proxyAgent('http://80.48.119.28:8080'),
      }
    });
    const data = await res.json();
    console.log(data); //it shows my ip
})();

Upvotes: -1

Related Questions