Using an Authenticated SOCKS5 Proxy in Node.js
By the ProxyV4 Engineering Team · 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.
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 uses | Package | Where the proxy goes |
|---|---|---|
http.get, https.request, Axios, ws, most older libraries | socks-proxy-agent | agent option (Axios: httpAgent and httpsAgent) |
fetch() or undici's request() | undici 7.23.0+ | dispatcher option, or setGlobalDispatcher() |
net sockets, custom TCP protocols | socks | SocksClient.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 proxyThe 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