Configuración de proxy en Node.js
Añade SotaProxy a cualquier cliente HTTP de Node.js - fetch, axios o got.
Node.js no admite la configuración de proxy de forma nativa mediante variables de entorno para todos los clientes HTTP. La mayoría de las librerías requieren un agente de proxy - un pequeño paquete que maneja el túnel de la conexión.
Guía de configuración
Instala https-proxy-agent
npm install https-proxy-agentEl paquete https-proxy-agent crea agentes HTTP compatibles con proxy para Node.js.
fetch nativo (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+ incluye fetch nativo. Pasa el agente de proxy en el objeto de opciones.
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);Pasa el agente de proxy como httpsAgent en el objeto de configuración de 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 usa un objeto agent con claves http y https. Pasa el agente de proxy bajo la clave https.
Automatízalo con la API de SotaProxy
Todo lo anterior funciona sin abrir el panel. Con una clave API, Node.js puede obtener credenciales de proxy actualizadas, comprar nuevos proxies y renovar los que caducan - directamente desde el código.
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.
Notas y consejos
- •Para geo-segmentación, añade _c_XX al nombre de usuario en la URL del proxy.
- •La rotación ocurre del lado del servidor - no necesitas cambiar la URL del proxy entre solicitudes para rotar la IP.
- •Prueba la conectividad: node -e "require('https-proxy-agent').HttpsProxyAgent; const {fetch} = globalThis; ..."
FAQ
¿Necesito un paquete de agente de proxy para Node.js?
Sí. El fetch nativo de Node.js y la mayoría de las librerías HTTP no admiten la configuración de proxy mediante parámetros de URL simples. El paquete https-proxy-agent maneja el túnel CONNECT para las solicitudes HTTPS.
¿Puedo establecer el proxy mediante variables de entorno en Node.js?
Algunas librerías (como undici, axios con plugin de proxy) admiten la variable de entorno HTTPS_PROXY. Consulta la documentación de tu librería. El enfoque del agente funciona en todas las librerías sin depender del entorno.
Integraciones relacionadas
Obtén tus credenciales de proxy
Regístrate, recarga tu saldo y copia tu endpoint en Node.js. Tarda menos de 5 minutos.
Empezar