How to Rotate Proxies in Node.js
By the Proxy11 team. Updated .
Getting a proxy address does not route anything. Node only uses it when you pass it through an agent, and that is the step most examples skip.
Use an agent to route HTTPS
HttpsProxyAgent opens the CONNECT tunnel that Node's HTTPS client sends the request through. Install it next to the SDK:
npm install proxy11 https-proxy-agent
const https = require("node:https");
const { HttpsProxyAgent } = require("https-proxy-agent");
const { ProxyClient } = require("proxy11");
const client = new ProxyClient(process.env.PROXY11_API_KEY);
const rotator = client.rotator({
country: "us",
proxyType: "anonymous",
autoRefresh: true,
});
async function checkProxy() {
const proxy = await rotator.next();
const agent = new HttpsProxyAgent(`http://${proxy}`);
return new Promise((resolve, reject) => {
const request = https.get("https://httpbin.org/ip", { agent }, (response) => {
let body = "";
response.setEncoding("utf8");
response.on("data", (chunk) => { body += chunk; });
response.on("end", () => resolve({ status: response.statusCode, body }));
});
request.setTimeout(15000, () => request.destroy(new Error("Request timed out")));
request.on("error", reject);
});
}
checkProxy().then(console.log).catch(console.error);
client.rotator() is synchronous. rotator.next() is async and resolves to an ip:port string. The 15-second timeout is only a starting point, so set one that suits your job.
Pool refresh behavior
The rotator keeps a local list and hands out one address at a time. autoRefresh fetches a new list when that one is empty. Set refreshAfter if you would rather refresh after a set number of picks.
Only mark a proxy dead when it is
Call markDead(proxy) when the connection to the proxy failed. An HTTP error from the target site means the proxy worked, so leave it in the pool.
API keys travel as query parameters, so don't share full request URLs, and limit who can read your request logs.