Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use proxy with Undici Fetch request in Node JS

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.
like image 499
Slick Avatar asked Nov 14 '25 09:11

Slick


1 Answers

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  });
like image 125
Paul-Alexandre Naud Avatar answered Nov 19 '25 06:11

Paul-Alexandre Naud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!