Using an Authenticated SOCKS5 Proxy in Node.js

· Updated:

Node.js has no built-in SOCKS5 support, so a Node.js SOCKS5 proxy always goes through a library: socks-proxy-agent for http, https and Axios, undici's Socks5ProxyAgent for fetch(), and the socks package for raw TCP sockets. All three accept a username and password. This guide shows each one, explains the socks5h:// detail that decides where DNS happens, and decodes the errors you will meet.

SOCKS5 and HTTP on one port

Pick the library by how your code makes requests

The right package depends on the API your code already calls, not on the proxy. Find your row and install one package.

Your code usesPackageWhere the proxy goes
http.get, https.request, Axios, ws, most older librariessocks-proxy-agentagent option (Axios: httpAgent and httpsAgent)
fetch() or undici's request()undici 7.23.0+dispatcher option, or setGlobalDispatcher()
net sockets, custom TCP protocolssocksSocksClient.createConnection() returns a connected socket

socks-proxy-agent with https and Axios

socks-proxy-agent builds a standard Node Agent that opens every connection through the SOCKS server. Credentials go in the URL, so percent-encode them if they contain @, : or /; the agent decodes them before the SOCKS handshake.

// npm install socks-proxy-agent
import https from 'node:https';
import { SocksProxyAgent } from 'socks-proxy-agent';

const user = encodeURIComponent('USER');
const pass = encodeURIComponent('PASS');
const agent = new SocksProxyAgent(`socks5h://${user}:${pass}@203.0.113.10:PORT`);

https.get('https://proxyv4.com/api/my-ip', { agent, timeout: 10_000 }, (res) => {
  let body = '';
  res.on('data', (chunk) => (body += chunk));
  res.on('end', () => console.log(res.statusCode, JSON.parse(body).ip));
}).on('error', (err) => console.error('request failed:', err.message));

The response should print the proxy's IP. Create the agent once and reuse it: each agent keeps its own pool of sockets, and building a new one per request throws that pool away.

socks5h:// or socks5://

The scheme decides who resolves the destination hostname. With socks5:// the agent looks the name up on your machine and sends the proxy an IP address. With socks5h:// (or a bare socks://) the hostname is passed to the proxy, which resolves it. Prefer socks5h://: the answer then matches the proxy's region, and your local resolver does not see each domain you visit.

Axios needs both agents and proxy: false

Axios picks httpAgent or httpsAgent by the target's scheme, so set both to the same SOCKS agent. Also set proxy: false; otherwise Axios may apply its own HTTP proxy handling from HTTP_PROXY or HTTPS_PROXY and fight with the agent.

import axios from 'axios';
import { SocksProxyAgent } from 'socks-proxy-agent';

const agent = new SocksProxyAgent('socks5h://USER:[email protected]:PORT');

const client = axios.create({
  httpAgent: agent,   // used for http:// targets
  httpsAgent: agent,  // used for https:// targets
  proxy: false,       // stop Axios applying its own proxy logic and env vars
  timeout: 10_000,
});

const { data } = await client.get('https://proxyv4.com/api/my-ip');
console.log(data.ip);

If you are fine with an HTTP proxy instead of SOCKS5, the Axios, fetch and Got setup guide shows the https-proxy-agent version and the matching code for Got.

Node fetch SOCKS5 authentication with undici

fetch() in Node is implemented by undici and ignores the agent option entirely, which is why socks-proxy-agent has no effect on it. Instead, undici 7.23.0 added Socks5ProxyAgent, a dispatcher you pass per request. Credentials can sit in the URL or in the username and password options; when both are present, the options win.

// npm install undici   (Socks5ProxyAgent needs 7.23.0 or later)
import { fetch, Socks5ProxyAgent } from 'undici';

const socks = new Socks5ProxyAgent('socks5://203.0.113.10:PORT', {
  username: 'USER',
  password: 'PASS',
});

const res = await fetch('https://proxyv4.com/api/my-ip', { dispatcher: socks });
console.log(res.status, (await res.json()).ip);

Two details trip people up. First, import fetch from the undici package rather than relying on the global one: Node's bundled undici may be a different major version from the one you installed, and a dispatcher from one version may not work with the other. Second, hostnames are always sent to the proxy for resolution, so there is no separate socks5h scheme to remember here.

Setting it for the whole process

If every request should leave through the same proxy, register the agent as the global dispatcher once at startup:

import { setGlobalDispatcher, Socks5ProxyAgent } from 'undici';

setGlobalDispatcher(new Socks5ProxyAgent('socks5://USER:[email protected]:PORT'));
// every undici fetch() in this process now leaves through the proxy

The class is marked experimental and prints a one-time ExperimentalWarning when constructed. To watch the handshake, run with NODE_DEBUG=undici:socks5-proxy. Full options are in the undici Socks5ProxyAgent reference.

What about undici ProxyAgent and fetch-socks?

undici ProxyAgent is the HTTP proxy dispatcher; recent releases also accept a socks5:// URL and hand it to Socks5ProxyAgent internally, but the dedicated class makes the intent obvious. The older fetch-socks package filled this gap before undici had native support; its README now points to the built-in class and the repository is archived, so avoid it in new code.

Raw TCP connections through SOCKS5

When you speak a protocol other than HTTP, such as SMTP testing, a custom game protocol or a database client that accepts an existing socket, use the socks package directly. It performs the SOCKS5 handshake, including username and password, and gives you back a connected net.Socket.

// npm install socks
import { SocksClient } from 'socks';

const { socket } = await SocksClient.createConnection({
  proxy: { host: '203.0.113.10', port: PORT, type: 5, userId: 'USER', password: 'PASS' },
  command: 'connect',
  destination: { host: 'example.com', port: 80 },
  timeout: 10_000,
});

socket.write('HEAD / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n');
socket.on('data', (d) => process.stdout.write(d));

socks-proxy-agent is itself built on this package, so the error messages below are the same in both.

Environment variables do not cover SOCKS5

Recent Node releases can read HTTP_PROXY, HTTPS_PROXY and NO_PROXY when you set NODE_USE_ENV_PROXY=1 or start with --use-env-proxy. That feature is documented for HTTP proxy URLs, so do not count on it for a SOCKS5 endpoint. Axios has its own environment handling for HTTP proxies, and neither socks-proxy-agent nor Socks5ProxyAgent reads any variable.

The practical rule: with SOCKS5 in Node, the proxy lives in code or in your own config variable (for example SOCKS_PROXY_URL) that you read and pass to the agent yourself. That also keeps NO_PROXY-style exclusions explicit. Use a plain fetch without a dispatcher, or a second Axios instance without the agents, for internal calls that should not go through the proxy.

Matching the proxy mode to your Node.js client

Every ProxyV4 proxy supports both protocols with username and password login, and you choose the mode per order: HTTP only, SOCKS5 only, or both on the same port. Both on one port is convenient in Node, because a service can use Socks5ProxyAgent for its fetch calls while a Puppeteer browser on the same server uses HTTP mode. Chromium cannot authenticate to a SOCKS5 proxy, so headless browsers need the HTTP side. Changing the mode later can move the proxy to a new port; copy the ip:port:user:pass line again when you do.

For long-running workers, a private datacenter IPv4 gives you one address per IP that only you use and that stays the same on renewal, with traffic that is not metered. It is not the tool for jobs that need a new IP per request (rotating proxies are not on sale) or for sites that only accept mobile carrier addresses. IPv6 proxies are a separate product that only works on IPv6-ready sites. Start with one IP from current pricing, run your real code against it, and add more once it behaves; a proxy that fails for a technical reason is handled under the refund policy as balance credit.

Errors you will see and what causes them

With undici, fetch throws a generic TypeError: fetch failed. The real reason is attached as cause, so always log it. The headings below quote the socks package, which socks-proxy-agent uses; undici has its own SOCKS code with different wording, but the causes are the same.

try {
  await fetch(url, { dispatcher: socks });
} catch (err) {
  // fetch wraps the real reason; the useful part is in err.cause
  console.error(err.message, '->', err.cause?.code, err.cause?.message);
}

Socks5 Authentication failed

The proxy rejected the username or password. Check for unencoded special characters in the URL, swapped user and password fields, or an order that is set to HTTP only, in which case the SOCKS handshake never gets as far as login.

ECONNREFUSED, ETIMEDOUT and Proxy connection timed out

ECONNREFUSED means nothing listens on that IP and port: a wrong port or a mode switch that moved the proxy. A timeout means packets are not getting through, often an outbound firewall on the host or a cloud security group that blocks high ports. Test the endpoint with the proxy checker and see the proxy timeout guide for more causes.

Socks5 proxy rejected connection

Login worked, but the proxy could not reach the destination. The text usually ends with a reason such as HostUnreachable or ConnectionRefused. Verify the destination host and port from another network before blaming the proxy, and with socks5:// make sure your local DNS did not resolve the name to an internal address.

Frequently asked questions

Does Node.js support SOCKS5 proxies natively?

No. Core http, https and the built-in fetch have no SOCKS client, so you add socks-proxy-agent, undici's Socks5ProxyAgent or the socks package.

Why does my agent option do nothing with fetch?

Node's fetch is built on undici and only understands a dispatcher. Pass a Socks5ProxyAgent as dispatcher, or register it with setGlobalDispatcher().

Is SOCKS5 faster than an HTTP proxy in Node.js?

For HTTPS requests the difference is negligible; both open one tunnel and TLS runs end to end. Choose by what your libraries support, not by speed.

Can I use one proxy for both SOCKS5 and HTTP clients in the same app?

Yes, if the proxy has both modes enabled on the same port, which ProxyV4 lets you choose per order. Point SOCKS clients at socks5h:// and HTTP clients at http:// with the same IP, port and credentials.

Does a SOCKS5 proxy work with WebSockets in Node.js?

Yes. The ws package accepts an agent option, so pass the same SocksProxyAgent you use for https requests.

SOCKS5 and HTTP on one port

Every ProxyV4 proxy supports SOCKS5 and HTTP(S) with username and password, and you can enable both on the same port per order. Start with one private IPv4 and test it in your Node.js code.

Compare plans

Related articles

Proxy setup
Authenticated proxies in Node.js: Axios, native fetch and Got
Route Node.js and TypeScript requests through an authenticated HTTP(S) proxy: https-proxy-agent for Axios, undici ProxyAgent for fetch, hpagent for Got.
Knowledge base
HTTP or SOCKS5: Picking the Proxy Protocol Your Software Needs
HTTP vs SOCKS5 proxy in plain terms: what each protocol carries, why HTTPS works through both, where UDP matters, and how to test which one a server speaks.
Proxy setup
Puppeteer with an authenticated proxy: launch flag plus login
Puppeteer proxy authentication, working example first: --proxy-server for the address, page.authenticate() for the login, then SOCKS5, contexts and fixes.
Products
Dedicated datacenter proxies: one private IPv4 per customer
Private IPv4 proxies in the US, Vietnam, Japan, South Korea, Singapore, the UK and Hong Kong. One tenant per IP, HTTP(S) and SOCKS5, no traffic metering.
Proxy setup
Set up your proxy, tool by tool
Proxy setup instructions you can follow with the dashboard open: antidetect browsers, operating systems, browser extensions and scraping libraries, all with authenticated HTTP(S) or SOCKS5.
Knowledge base
Configuring a reqwest Proxy for Rust HTTP Clients
Configure a reqwest proxy in Rust: Proxy::all with basic_auth, the socks Cargo feature for socks5h, env vars, NO_PROXY and the errors behind failed tunnels.
Knowledge base
Routing Ruby HTTP Requests Through an Authenticated Proxy
Ruby Net::HTTP proxy setup with a username and password, plus Faraday and HTTParty options, the https_proxy quirk, SOCKS via socksify and common exceptions.
Knowledge base
Setting Up wget Behind a Proxy That Needs a Login
Set a wget proxy username and password with flags, http_proxy and https_proxy variables or wgetrc, then fix 407 errors and handle SOCKS5 downloads.
Free tools
Check proxies in bulk: status, exit IP and latency
Free online proxy checker: paste up to 100 ip:port:user:pass lines and see which proxies work, their exit IP and latency, plus what each failure result means.
Products
Static ISP proxies: residential IPs on consumer networks
Static ISP proxies in the United States and Vietnam: fixed IPs registered to consumer internet providers, rented to one customer, with unmetered traffic.