Use proxy with Undici Fetch request in Node JS

1.3k Views Asked by At

Question

I'm unsure about how to use a proxy with Undici fetch. I hope to use separate proxies for any fetch request with username and password authentication if applicable. I've found some documentation for proxies, but I haven't seen much about using proxies with the fetch api.

Solution

As for a good solution I'd hope for a code example to perform a simple get request to a site (e.g. to ifconfig.me) using a proxy and instructions on how to include a username and password with that proxy.

The solution should do the same function as the code below but using a proxy:

const { fetch } = require("undici");

const req = await fetch('https://ifconfig.me/all');
const res = await req.text();
Node version 18 is being used.
1

There are 1 best solutions below

0
On

Solution found here https://github.com/nodejs/undici/blob/e461407c63e1009215e13bbd392fe7919747ab3e/docs/api/ProxyAgent.md

In my case I use

const client = new ProxyAgent(`http://${proxy.user}:${proxy.pass}@${proxy.host}:${proxy.port}`);
const response = await fetch(urlRequested, {  dispatcher: client  });