Code and command line
Node.js proxy setup
Node.js has no proxy setting of its own. The built-in fetch ignores the usual environment variables by default, and the http module needs an agent. In practice you choose one of two routes: the undici ProxyAgent for fetch, or the https-proxy-agent package for axios, got and the core https module.
Both routes are short. The differences are in how they take the login, how they reuse connections, and which one fits the library you already use.
What do you need before adding a proxy in Node.js?
Tick these off before the first step. Your login and password appear in your account once the first top-up of $40 or more has been credited.
| Requirement | Detail |
|---|---|
| Node.js 18 or newer | Ships a global fetch built on undici. |
| undici from npm | npm i undici. Import fetch and ProxyAgent from the same package so their versions match. |
| Or https-proxy-agent | npm i https-proxy-agent axios for the axios route. |
| Login and password | Login such as tp7k2m9_country-us, password in an environment variable. |
Where do the proxy host, port and login go in Node.js?
Work through the steps in order. Swap YOUR_PASSWORD for your proxy password and tp7k2m9 for your account name.
fetch through an undici ProxyAgent
Create a ProxyAgent with the gateway URL and a
tokenholding the Basic credentials, then pass it asdispatcheron each fetch call. Using thetokenoption avoids putting the password into a URL, so no encoding is needed.import { fetch, ProxyAgent } from 'undici'; const login = 'tp7k2m9_country-us'; const password = process.env.TOPPROXY_PASSWORD ?? 'YOUR_PASSWORD'; const dispatcher = new ProxyAgent({ uri: 'http://proxy.topproxy.shop:8080', token: 'Basic ' + Buffer.from(login + ':' + password).toString('base64'), }); const res = await fetch('https://ipinfo.io/json', { dispatcher }); console.log(await res.json());Tip.Mixing the global fetch with a ProxyAgent from a different undici version can fail with odd errors. Import both from the npm package.
axios with https-proxy-agent
axios has its own proxy option, but it handles https targets poorly. Give axios an
HttpsProxyAgentashttpsAgentand switch its built-in proxy off withproxy: false. Here the credentials sit in the URL, so encode the password.import axios from 'axios'; import { HttpsProxyAgent } from 'https-proxy-agent'; const pw = encodeURIComponent(process.env.TOPPROXY_PASSWORD ?? 'YOUR_PASSWORD'); const agent = new HttpsProxyAgent('http://tp7k2m9_country-us:' + pw + '@proxy.topproxy.shop:8080'); const { data } = await axios.get('https://ipinfo.io/json', { httpsAgent: agent, proxy: false }); console.log(data);SOCKS5 with remote DNS
For tools that need SOCKS5,
socks-proxy-agentworks with axios and the core modules. Thesocks5hscheme makes the exit resolve hostnames.import axios from 'axios'; import { SocksProxyAgent } from 'socks-proxy-agent'; const pw = encodeURIComponent(process.env.TOPPROXY_PASSWORD ?? 'YOUR_PASSWORD'); const agent = new SocksProxyAgent('socks5h://tp7k2m9_country-nl:' + pw + '@proxy.topproxy.shop:1080'); const { data } = await axios.get('https://ipinfo.io/json', { httpsAgent: agent, httpAgent: agent, proxy: false }); console.log(data.country);Build logins with one function
Keep the login format in a single helper and create agents from it. Cache agents per login so repeated calls reuse connections instead of opening new tunnels each time.
import { ProxyAgent } from 'undici'; const cache = new Map(); export function topproxy({ country = 'us', city, session, life = 30 } = {}) { let login = 'tp7k2m9_country-' + country; if (city) login += '_city-' + city; if (session) login += '_session-' + session + '_life-' + life; if (!cache.has(login)) { const token = 'Basic ' + Buffer.from(login + ':' + process.env.TOPPROXY_PASSWORD).toString('base64'); cache.set(login, new ProxyAgent({ uri: 'http://proxy.topproxy.shop:8080', token })); } return cache.get(login); }
How can you confirm the proxy is active in Node.js?
Fetch ipinfo.io with the agent and print the address and country. Then fetch it once without the agent: the two addresses should differ.
const info = await (await fetch('https://ipinfo.io/json', { dispatcher: topproxy({ country: 'us' }) })).json();
console.log(info.ip, info.city, info.country);The response shown here is shortened to the fields that matter. The region and time zone follow the exit, in this case Netherlands.
{
"ip": "198.51.100.47",
"city": "Amsterdam",
"region": "North Holland",
"country": "NL",
"timezone": "Europe/Amsterdam"
}198.51.100.47 is an address reserved for documentation. A live check prints a real exit.
How do you switch between rotating and held IPs in Node.js?
An agent keeps connections alive, so calls through one cached rotating agent can share an exit for a while. When every request should get a new address, create a fresh agent per request or close it with agent.close(). When a flow needs one address, use a session login.
const token = 'Basic ' + Buffer.from('tp7k2m9_country-us:' + process.env.TOPPROXY_PASSWORD).toString('base64');
const fresh = new ProxyAgent({ uri: 'http://proxy.topproxy.shop:8080', token });
await fetch(url, { dispatcher: fresh });
await fresh.close();How the login is put together
Every setting lives in the login, joined with underscores. Nothing else in Node.js changes when you switch location or session.
| Part | Meaning | Rule |
|---|---|---|
| tp7k2m9 | Your account name | Always first. Yours is shown in your account and replaces tp7k2m9 in every example here. |
| _country-us | Exit country | Two-letter code in lowercase. 64 countries to choose from. |
| _city-new-york | Exit city, optional | Lowercase, spaces become hyphens. 172 cities in total. |
| _session-a1b2c3 | Session name, optional | Letters and digits you pick. Same name, same exit. New name, new exit. |
| _life-30 | Session life in minutes | Only with a session. Residential 1 to 120 minutes, mobile 1 to 60 minutes, long session ISP up to 12 hours (life 720). |
All parts togethertp7k2m9_country-us_city-new-york_session-a1b2c3_life-30
How do you choose an exit country or city in Node.js?
Pass a country code and, if needed, a city to the helper. The login becomes tp7k2m9_country-sg_city-singapore for the city example.
await fetch(url, { dispatcher: topproxy({ country: 'sg' }) });Codes and city values for all 64 countries are listed on the proxy locations pages.
How do you fix a 407 or connection error in Node.js?
Find the line that matches what you see. Most problems come down to the login, the port or the network you are on.
| Symptom | Likely cause | Fix |
|---|---|---|
Proxy response (407) !== 200 when HTTP Tunneling | undici received a login refusal from the gateway. | Check the token: it must be the word Basic, a space, and base64 of login:password. |
UND_ERR_INVALID_ARG or dispatcher errors | Global fetch and an undici ProxyAgent from a different version were mixed. | Import fetch from undici as well. |
| axios returns your own IP | The agent was set as httpAgent only, or axios used its own proxy option. | Set httpsAgent and proxy: false. |
ECONNRESET under heavy load | Too many tunnels opened at once from one process. | Reuse agents per login and cap concurrency with a queue. |
Still stuck? Run the same login through the cURL check. If cURL connects, the issue is in the Node.js settings. If it does not, write to support with the error text.
What kind of proxy pairs well with Node.js?
All products sit behind the same gateway and share one prepaid balance, so moving from one to another means buying the other product and changing the login, nothing more.
- Rotating Residential ProxiesA new household address per connection for Node collectors.$0.23 per GB
- Private Datacenter ProxiesUnmetered traffic on fixed IPs for API polling and high request counts.$0.17 per IP per month
- Long Session ISP ProxiesHold an ISP address for hours across a long worker process.$0.13 per GB
Calling pages from code at scale? The TopProxy API docs cover the Scraping API, which renders pages and retries on its own.
What else do Node.js users ask about proxies?
Does Node read HTTPS_PROXY automatically?
Not by default. Recent Node versions can honor proxy environment variables when started with NODE_USE_ENV_PROXY=1, but an explicit agent or dispatcher is clearer and works on every supported version.
Should I use undici or https-proxy-agent?
Use undici when you call fetch. Use https-proxy-agent when you use axios, got, or the core https module. Both send the same CONNECT request to the gateway.
Can I set one dispatcher for all fetch calls?
Yes. setGlobalDispatcher from undici applies an agent to every fetch made with undici. It suits scripts that use a single login. For several logins, pass the dispatcher per call.
How do I add the login when credentials are in the URL?
Percent-encode the password with encodeURIComponent before building the URL. With the undici token option you skip this step entirely.
Does this work with TypeScript?
Yes. undici, https-proxy-agent and socks-proxy-agent all ship type definitions, and the examples run unchanged as .ts files with tsx or a build step.
Related setup guides
- PuppeteerThe --proxy-server switch plus page.authenticate, one browser per location, and a clean way to switch sessions.
- PlaywrightProxy server, username and password at launch or per context, in Node.js and Python, with one location per context.
- cURLOne terminal command to prove your login works, then SOCKS5 with remote DNS and a reusable config file.
- Python RequestsA proxies dictionary, a Session with retries, SOCKS5 through PySocks and a pool of sticky logins.
Ready to connect Node.js?
Open an account, add $40 or more in crypto, and your login and password are waiting in the account area.