Налаштування проксі у Node.js
Додайте SotaProxy у будь-який HTTP-клієнт Node.js - fetch, axios або got.
Node.js не підтримує конфігурацію проксі нативно через змінні оточення для всіх HTTP-клієнтів. Більшості бібліотек потрібен проксі-агент - невеликий пакет, який обробляє тунелювання з’єднання.
Посібник із налаштування
Встановіть https-proxy-agent
npm install https-proxy-agentПакет https-proxy-agent створює HTTP-агенти з підтримкою проксі для Node.js.
Нативний fetch (Node 18+)
import { HttpsProxyAgent } from 'https-proxy-agent';
const proxyUrl = 'http://YOUR_USERNAME:YOUR_PASSWORD@proxy.sotaproxy.com:10000';
const agent = new HttpsProxyAgent(proxyUrl);
const response = await fetch('https://httpbin.org/ip', { agent });
const data = await response.json();
console.log(data);Node 18+ містить нативний fetch. Передайте проксі-агент в об’єкті опцій.
axios
import axios from 'axios';
import { HttpsProxyAgent } from 'https-proxy-agent';
const proxyUrl = 'http://YOUR_USERNAME:YOUR_PASSWORD@proxy.sotaproxy.com:10000';
const httpsAgent = new HttpsProxyAgent(proxyUrl);
const response = await axios.get('https://httpbin.org/ip', { httpsAgent });
console.log(response.data);Передайте проксі-агент як httpsAgent в об’єкті конфігурації axios.
got
import got from 'got';
import { HttpsProxyAgent } from 'https-proxy-agent';
const proxyUrl = 'http://YOUR_USERNAME:YOUR_PASSWORD@proxy.sotaproxy.com:10000';
const agent = { https: new HttpsProxyAgent(proxyUrl) };
const response = await got('https://httpbin.org/ip', { agent });
console.log(response.body);got використовує об’єкт agent із ключами http і https. Передайте проксі-агент під ключем https.
Автоматизуй через SotaProxy API
Усе описане вище працює без відкриття дашборда. З API-ключем Node.js може отримувати свіжі дані проксі, купувати нові та продовжувати ті, що спливають, - прямо з коду.
const API = 'https://api.sotaproxy.com/api/v1'
const H = { Authorization: 'Bearer sk_live_your_key' }
// Every active proxy on your account - no copy-pasting credentials
const { proxies } = await (await fetch(`${API}/proxies`, { headers: H })).json()
const p = proxies[0]
const proxyUrl = `http://${p.login}:${p.password}@${p.ip}:${p.portHttp}`
// Buy more when you scale (price-check first with POST /quote)
await fetch(`${API}/orders`, {
method: 'POST',
headers: { ...H, 'Content-Type': 'application/json', 'Idempotency-Key': 'my-unique-order-id' },
body: JSON.stringify({ product: 'ipv4', countryId: 565, periodId: '1m', quantity: 5 }),
})Agents, not settings
Node has no global proxy switch. Every HTTP client takes an agent, and the agent carries the address and the credentials:
https-proxy-agent covers HTTP and HTTPS targets. socks-proxy-agent covers SOCKS5, and its socks5h equivalent resolves DNS on our side.
An agent per identity
Build the agent once per session id and reuse it. Creating one per request throws away connection reuse and slows the run:
Node: pooled agents with fetch
import { HttpsProxyAgent } from 'https-proxy-agent';
const BASE = 'proxy.sotaproxy.com:10000';
const agents = new Map();
function agentFor(sessionId, country = 'US') {
if (!agents.has(sessionId)) {
const login = `login_c_${country}_s_${sessionId}_ttl_15m`;
agents.set(sessionId, new HttpsProxyAgent(`http://${login}:password@${BASE}`));
}
return agents.get(sessionId);
}
const res = await fetch('https://example.com', {
agent: agentFor(4),
headers: { 'Accept-Encoding': 'gzip' },
signal: AbortSignal.timeout(30000),
});- Node 18 fetch ignores the agent option. Use undici with a ProxyAgent, or node-fetch, or axios with httpsAgent.
- Always pass a timeout signal. Node will otherwise wait indefinitely on a stalled route.
- Keep agents in a map keyed by session id. Rebuilding them per request costs a TLS handshake every time.
- For SOCKS5 with remote DNS use socks5h in the URL, the same rule as everywhere else.
Node specifics
Global fetch quietly ignores agents
It is the most common confusion in Node 18 and later. The request goes out directly and looks like a proxy failure.
Agent per request
Each new agent opens a new connection to us. Under load this alone can halve your throughput.
No timeout by default
A single hung request holds a worker forever. AbortSignal.timeout is one line and prevents it.
Credentials in logs
The proxy URL contains the password. Strip it before logging, or a crash report leaks the account.
Нотатки та поради
- •Для гео-таргетингу додайте _c_XX до імені користувача в URL проксі.
- •Ротація відбувається на боці сервера - міняти URL проксі між запитами для ротації IP не потрібно.
- •Перевірте з’єднання: node -e "require('https-proxy-agent').HttpsProxyAgent; const {fetch} = globalThis; ..."
FAQ
Чи потрібен пакет проксі-агента для Node.js?
Так. Нативний fetch у Node.js і більшість HTTP-бібліотек не підтримують конфігурацію проксі через прості параметри URL. Пакет https-proxy-agent обробляє CONNECT-тунелювання для HTTPS-запитів.
Чи можна задати проксі через змінні оточення в Node.js?
Деякі бібліотеки (наприклад, undici, axios із плагіном проксі) підтримують змінну оточення HTTPS_PROXY. Дивіться документацію вашої бібліотеки. Підхід через агент працює в усіх бібліотеках без залежності від оточення.
Схожі інтеграції
Отримай облікові дані проксі
Зареєструйся, поповни баланс і скопіюй ендпоінт у Node.js. Займе менше 5 хвилин.
Почати