Programming languages

How to use a proxy in Node.js

Node.js runs most JavaScript scrapers, bots and backend integrations. Its HTTP clients do not read proxy settings on their own, so you attach the proxy explicitly: a dispatcher for the built-in fetch, or an agent for node:https, axios and most other libraries.

The built-in fetch is powered by undici and ignores the agent option that older tutorials use. This guide shows the right object for each client, then sticky sessions, SOCKS5 and parallel workers.

Updated 23 November 2026

What you need
Hostgate.firstproxy.shop
HTTP / HTTPS port8000
SOCKS5 port9000
Usernameuser-country-us
PasswordYOUR_TOKEN

HTTP on port 8000 works with undici and https-proxy-agent. SOCKS5 on port 9000 works through socks-proxy-agent. Your username and token appear on the Proxy setup page of your dashboard after your first order.

Setup

How do I connect Node.js to a proxy?

Follow the steps in order. Replace YOUR_TOKEN with the token from your dashboard and change the country, city or session in the username to suit the job.

  1. Install the proxy helpers

    Node.js 18 or later is assumed. Install only what your client needs: undici for fetch, https-proxy-agent for agent-based clients, socks-proxy-agent for SOCKS5.

    npm i undici
    npm i axios https-proxy-agent
    npm i socks-proxy-agent
  2. Proxy the built-in fetch with undici ProxyAgent

    Pass a ProxyAgent as dispatcher. Sending the credentials in the token option as a Basic header keeps special characters in the token from breaking a URL. Import fetch from undici as well, so the fetch and the dispatcher come from the same version.

    import { fetch, ProxyAgent } from 'undici'
    
    const user = 'user-country-us'
    const dispatcher = new ProxyAgent({
      uri: 'http://gate.firstproxy.shop:8000',
      token: 'Basic ' + Buffer.from(user + ':YOUR_TOKEN').toString('base64'),
    })
    
    const res = await fetch('https://ipinfo.io/json', { dispatcher })
    console.log(res.status, await res.json())

    To proxy every fetch in the process, call setGlobalDispatcher(dispatcher) from undici once at startup.

  3. Use axios or node:https with https-proxy-agent

    Give axios the agent as httpsAgent and set proxy: false. The built-in axios proxy option does not tunnel HTTPS reliably, and leaving it on makes axios also read proxy environment variables.

    import axios from 'axios'
    import { HttpsProxyAgent } from 'https-proxy-agent'
    
    const agent = new HttpsProxyAgent('http://user-country-us:YOUR_TOKEN@gate.firstproxy.shop:8000')
    
    const res = await axios.get('https://ipinfo.io/json', {
      httpsAgent: agent,
      proxy: false,
      timeout: 30000,
    })
    console.log(res.data)
  4. Target a city and keep a sticky session

    Generate a session name per worker or per account, and put the city in lowercase with hyphens. Reuse the same agent for all calls of that session.

    import { randomBytes } from 'node:crypto'
    import { fetch, ProxyAgent } from 'undici'
    
    function sessionAgent(country, city, minutes = 15) {
      const sid = randomBytes(4).toString('hex')
      let user = 'user-country-' + country
      if (city) user += '-city-' + city
      user += '-session-' + sid + '-ttl-' + minutes + 'm'
      return new ProxyAgent({
        uri: 'http://gate.firstproxy.shop:8000',
        token: 'Basic ' + Buffer.from(user + ':YOUR_TOKEN').toString('base64'),
      })
    }
    
    const dispatcher = sessionAgent('us', 'seattle', 20)
    for (let i = 0; i < 3; i++) {
      const r = await fetch('https://ipinfo.io/ip', { dispatcher })
      console.log((await r.text()).trim())
    }

    The three lines printed should show the same IP. A new call to sessionAgent creates a new session and a new IP.

  5. Connect over SOCKS5

    socks-proxy-agent works anywhere an agent is accepted. Use the socks5h scheme so the proxy resolves hostnames, and pass the agent for both http and https targets in axios.

    import axios from 'axios'
    import { SocksProxyAgent } from 'socks-proxy-agent'
    
    const agent = new SocksProxyAgent('socks5h://user-country-de:YOUR_TOKEN@gate.firstproxy.shop:9000')
    const res = await axios.get('https://ipinfo.io/json', {
      httpAgent: agent,
      httpsAgent: agent,
      proxy: false,
    })
    console.log(res.data)
Test

How do I check that the proxy works?

Call ipinfo.io/json through the dispatcher or agent and log the parsed JSON. If the IP is your own, the client ignored the proxy object you passed.

A working proxy returns a response like the one shown, trimmed to the main fields. The IP belongs to the exit, the city and country follow your username, and the time zone is where that IP is located, here United States.

const res = await fetch('https://ipinfo.io/json', { dispatcher })
console.log(await res.json())
ipinfo.io/json response
{
  "ip": "203.0.113.24",
  "city": "New York",
  "country": "US",
  "timezone": "America/New_York"
}

203.0.113.24 is a documentation address. Your result shows a real exit IP.

Targeting

How do I set country, city and session in the username?

All targeting is written into the username, so Node.js needs no extra settings to change location. Parts are joined with hyphens in this order after your proxy user. The password is always your token.

Proxy username parts
PartFormatExampleRule
Country-country-{cc}-country-usRequired. Two-letter country code in lowercase. 64 countries are available.
City-city-{city}-city-new-yorkOptional. City name in lowercase, spaces become hyphens. 172 cities are available.
Session-session-{id}-session-a1b2c3Optional. Any letters and digits you choose. The same id keeps the same IP, a new id gets a new IP.
Session length-ttl-{minutes}m-ttl-30mUsed with a session. Residential 1 to 120 minutes, mobile 1 to 60, long-acting ISP up to 720 (12 hours).
Full usernameuser-country-us-city-new-york-session-a1b2c3-ttl-30m

Find country codes and city values on the proxy locations page.

Troubleshooting

Node.js proxy errors and fixes

The problems people run into most often with Node.js, with the message you are likely to see and how to solve it.

The request leaves from my own IP

The built-in fetch silently ignores an agent option. Use dispatcher with undici ProxyAgent, or switch to a client that accepts agents, such as axios or node:https.

Proxy response (407) !== 200 when HTTP Tunneling

undici received a 407 from the gateway. Rebuild the Basic token from the exact username and token, and check that the username has no stray spaces.

UND_ERR_CONNECT_TIMEOUT or ETIMEDOUT

Set an AbortSignal.timeout(30000) signal on fetch, or timeout in axios, and retry with a new session name. Check that outbound port 8000 or 9000 is open on your host.

axios returns 400 or a TLS error through the proxy

The axios proxy option is still active. Set proxy: false and pass the agent as httpsAgent.

invalid onRequestStart method or similar dispatcher errors

A ProxyAgent from the undici package was passed to the fetch built into a different Node.js release. Import both fetch and ProxyAgent from undici so their versions match.

FAQ

Node.js proxy questions

Short answers to what people ask most about using a proxy with Node.js.

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

Install undici, create new ProxyAgent({ uri: "http://gate.firstproxy.shop:8000", token: "Basic " + base64 of username:YOUR_TOKEN }), and pass it as the dispatcher option to fetch. The agent option is ignored by the built-in fetch.

Which proxy agent should I use with axios?

Use HttpsProxyAgent from https-proxy-agent as httpsAgent and set proxy: false. For SOCKS5, use SocksProxyAgent for both httpAgent and httpsAgent.

Does Node.js read HTTP_PROXY automatically?

Not by default. Most clients need the proxy passed in code. Some libraries read environment variables themselves, which is why axios users set proxy: false to avoid surprises.

How do I run many sessions in parallel in Node.js?

Create one ProxyAgent or HttpsProxyAgent per session name and give each worker its own. Requests on the same agent share the session IP, and different agents get different IPs.

Get your token and run the first Node.js request

Create an account, top up from $40 with crypto, and copy the gateway, username and token from the dashboard.