How to Use a Proxy in Node.js (fetch, axios, got and Puppeteer)

Short answer: Node’s built-in fetch ignores proxy settings by default. Use undici’s ProxyAgent as the dispatcher, or https-proxy-agent with axios and got. Put the credentials in the proxy URL (http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}), set a timeout on every request, and do not retry a 407.

This guide covers fetch, axios, got and Puppeteer, plus rotation, retries and common errors. It is part of our guide to proxies for web scraping. Other languages: Python requests proxy, Scrapy proxy setup, Playwright proxy setup and Selenium proxy setup.

Use proxies for public data and legitimate testing only: market research, price monitoring, ad verification, SEO checks and QA. Respect each site’s terms and robots.txt.

Prerequisites

  • Node.js 18 or newer. The examples use ES modules, so use .mjs files or set "type": "module" in package.json.
  • Proxy credentials from your dashboard: username, password, host and port. New to these terms? Read what a proxy host and port are.

fetch with undici

npm i undici
import { fetch, ProxyAgent } from "undici";

const dispatcher = new ProxyAgent("http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}");

const res = await fetch("https://httpbin.org/ip", {
  dispatcher,
  signal: AbortSignal.timeout(30000),
});
console.log(res.status, await res.json());

The returned origin should be the proxy’s IP, not yours. For other ways to check a proxy, see how to test proxies.

Use the fetch exported by the undici package together with its ProxyAgent. Mixing Node’s global fetch with an agent from the npm package can fail on some Node and undici version combinations, so import both from the same place.

Set the proxy for every request in the process

import { setGlobalDispatcher, ProxyAgent, fetch } from "undici";

setGlobalDispatcher(new ProxyAgent("http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"));

const res = await fetch("https://httpbin.org/ip");
console.log(await res.json());

This is convenient for scripts. In larger apps, pass the dispatcher explicitly so that internal calls (databases, your own APIs) do not go through the proxy by accident.

axios

axios has a proxy option, but it is unreliable for HTTPS targets through an HTTP proxy. A dedicated agent is more predictable:

npm i axios https-proxy-agent
import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";

const agent = new HttpsProxyAgent("http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}");

const res = await axios.get("https://httpbin.org/ip", {
  httpAgent: agent,
  httpsAgent: agent,
  proxy: false, // stop axios from applying its own proxy handling
  timeout: 30000,
});
console.log(res.status, res.data);

The proxy: false line matters. Without it, axios can also read HTTP_PROXY and HTTPS_PROXY from the environment and conflict with the agent.

got

got v12 and newer is ESM-only and takes agents through the agent option:

npm i got https-proxy-agent
import got from "got";
import { HttpsProxyAgent } from "https-proxy-agent";

const agent = new HttpsProxyAgent("http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}");

const data = await got("https://httpbin.org/ip", {
  agent: { http: agent, https: agent },
  timeout: { request: 30000 },
}).json();
console.log(data);

Puppeteer

Pass the proxy server at launch and authenticate the page with the username and password:

npm i puppeteer
import puppeteer from "puppeteer";

const browser = await puppeteer.launch({
  args: ["--proxy-server=http://{PROXY_HOST}:{PORT}"],
});

try {
  const page = await browser.newPage();
  await page.authenticate({ username: "USERNAME", password: "PASSWORD" });
  await page.goto("https://httpbin.org/ip", { timeout: 60000 });
  console.log(await page.evaluate(() => document.body.innerText));
} finally {
  await browser.close();
}

Credentials do not go inside --proxy-server; Chrome ignores them there. If you can choose the tool, Playwright accepts the username and password directly in its proxy option.

Environment variables

For scripts and containers, keep credentials out of the source code:

const PROXY_URL = process.env.PROXY_URL; // "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"
if (!PROXY_URL) throw new Error("PROXY_URL is not set");

Run it with PROXY_URL="http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}" node app.mjs. Never commit real credentials to a repository.

Special characters in the password

If the password contains characters such as @, : or /, encode the credentials before building the URL:

const user = encodeURIComponent("USERNAME");
const pass = encodeURIComponent("PASSWORD");
const PROXY_URL = `http://${user}:${pass}@{PROXY_HOST}:{PORT}`;

In real code, replace {PROXY_HOST} and {PORT} with your values. Inside a template string, write them as plain text, not as ${...}.

Rotation

If your plan gives you a rotating gateway, one proxy URL is enough, and new IPs appear on the schedule or per connection that you set. USA 4G/5G proxies rotate every 5, 10 or 30 minutes depending on your setting. Check your dashboard for the exact options.

If you have a list of endpoints, cycle through them:

import { fetch, ProxyAgent } from "undici";

const agents = [
  new ProxyAgent("http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"),
  new ProxyAgent("http://USERNAME:PASSWORD@{PROXY_HOST_2}:{PORT_2}"),
];
let i = 0;
const nextAgent = () => agents[i++ % agents.length];

for (let page = 1; page <= 3; page++) {
  const res = await fetch(`https://httpbin.org/anything?page=${page}`, {
    dispatcher: nextAgent(),
    signal: AbortSignal.timeout(30000),
  });
  console.log(page, res.status);
}

Create the agents once and reuse them. Creating a new agent per request wastes connections. When several requests must share one IP, use one agent for the whole flow, or a sticky session or static IP. For trade-offs, see rotating vs static residential proxies.

Retry with backoff

import { fetch, ProxyAgent } from "undici";

const dispatcher = new ProxyAgent("http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}");
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function getWithRetry(url, retries = 4) {
  for (let attempt = 0; attempt < retries; attempt++) {
    try {
      const res = await fetch(url, {
        dispatcher,
        signal: AbortSignal.timeout(30000),
      });
      if (res.status === 407) throw new Error("407: check USERNAME/PASSWORD");
      if (res.status === 429 || res.status >= 500) {
        await res.body?.cancel();
        await sleep(2 ** attempt * 1000 + Math.random() * 500);
        continue;
      }
      return res;
    } catch (err) {
      if (String(err.message).startsWith("407")) throw err; // do not retry credentials
      await sleep(2 ** attempt * 1000 + Math.random() * 500);
    }
  }
  throw new Error(`Failed after ${retries} attempts: ${url}`);
}

const res = await getWithRetry("https://httpbin.org/ip");
console.log(res.status, await res.json());

Keep concurrency low. A small pool (for example 5 to 10 parallel requests) with a delay between batches is kinder to the target and cheaper on per-GB plans.

Save bandwidth on per-GB plans

  • Request only the URLs you need, and cache responses you already have.
  • In Puppeteer, block images, fonts and media with request interception (page.setRequestInterception(true)), after testing that your target still renders what you need.
  • Prefer lightweight HTTP clients to headless browsers when the data is in the HTML or in a public JSON endpoint that the site’s terms allow you to use.

On residential proxies you pay per GB, while USA 4G/5G mobile proxies have unlimited bandwidth and are billed by time.

Common errors and fixes

SymptomLikely causeFix
Your own IP is returnedProxy not applied: Node’s global fetch ignores it, or axios used its own proxy handlingPass the dispatcher or agent, and set proxy: false in axios
407 Proxy Authentication RequiredWrong credentials, unencoded special characters, or IP not whitelistedCheck username and password, encode them, check the whitelist
ECONNREFUSEDWrong host or portVerify {PROXY_HOST} and {PORT}
ETIMEDOUT or UND_ERR_CONNECT_TIMEOUTNetwork, firewall or slow pathTest from another network, raise the timeout, lower concurrency
TimeoutError from AbortSignal.timeoutSlow target or heavy pageRaise the timeout, retry with backoff
ERR_REQUIRE_ESM with gotgot v12+ is ESM-only and was loaded with require()Use import or an .mjs file
HTTP 429Too many requests to the targetLower concurrency, add delays, honor Retry-After

Exact error names vary between Node.js, undici and library versions, so log the full error object once to see what your versions produce. A fuller breakdown is in proxy errors: what each one means and how to fix it.

Next steps

Load one page through the proxy, confirm the exit IP, then scale gradually and watch your error rate and bandwidth. For choosing between residential, mobile and ISP proxies and estimating cost, read proxies for web scraping.

Need proxies to test with? Compare residential proxies (per GB), USA 4G/5G mobile proxies (per day, unlimited bandwidth) and static ISP proxies (30-day plans), or see the pricing page. Every plan comes with a 24-hour money-back guarantee.

See residential plans

FAQ

How do I use a proxy with fetch in Node.js?

Node’s built-in fetch does not read proxy settings by default. Install undici and pass new ProxyAgent("http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}") as the dispatcher option, using the fetch exported by undici.

How do I use a proxy with axios?

Create an HttpsProxyAgent from the https-proxy-agent package, pass it as both httpAgent and httpsAgent, and set proxy: false so axios does not apply its own proxy handling.

How do I use a proxy with username and password in Node.js?

Put the credentials in the proxy URL. If the password contains special characters, encode it with encodeURIComponent first. In Puppeteer, use page.authenticate() instead.

Why does my Node.js request still show my own IP?

The proxy was not applied. Global fetch ignores proxy settings unless you pass a dispatcher, and axios can bypass an agent if proxy: false is missing. Confirm with https://httpbin.org/ip.

How do I rotate proxies in Node.js?

Use a rotating gateway from your provider, so one proxy URL gives you new IPs, or keep a list of agents and cycle through them. Create the agents once and reuse them, and keep one agent per flow when requests must share an IP.

Should I retry a 407 error?

No. A 407 means the proxy rejected your credentials or your IP. Fix the username, password or whitelist instead of retrying.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.