Node.js SSL Proxy Examples
Complete guide with working examples for configuring SSL proxy in Node.js using axios, fetch, and undici libraries
What is an SSL Proxy?
An SSL proxy is a proxy server that handles encrypted HTTPS connections. When you make HTTP requests through an SSL proxy, the proxy terminates the SSL connection, processes the request, and establishes a new SSL connection to the target server.
Use Case: SSL proxies are commonly used for security compliance, IP whitelisting, and maintaining consistent IP addresses for API access.
Axios with SSL Proxy
Basic SSL Proxy Configuration
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
// Your SSL proxy configuration
const PROXY_HOST = "192.168.1.100"; // Your static IP
const PROXY_PORT = 8080;
const PROXY_USER = "your_proxy_username";
const PROXY_PASS = "your_proxy_password";
// Create proxy agent for SSL
const proxyAgent = new HttpsProxyAgent(
`https://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`
);
// Create axios instance with SSL proxy
const client = axios.create({
httpsAgent: proxyAgent,
timeout: 30000, // 30 seconds
});
async function fetchData(url) {
try {
const response = await client.get(url);
console.log(`Status: ${response.status}`);
console.log(`Response: ${JSON.stringify(response.data, null, 2).slice(0, 100)}...`);
return response.data;
} catch (error) {
if (error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT') {
console.error('Proxy connection error:', error.message);
} else {
console.error('Request failed:', error.message);
}
return null;
}
}
// Usage example
(async () => {
const result = await fetchData('https://api.example.com/data');
if (result) {
console.log('Request successful!');
}
})();
SSL Certificate Handling
const axios = require('axios');
const https = require('https');
const { HttpsProxyAgent } = require('https-proxy-agent');
// SSL proxy configuration
const proxyAgent = new HttpsProxyAgent(
`https://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`
);
// Custom CA for self-signed certificates
const customCA = fs.readFileSync('/path/to/ca-certificate.pem');
// Create axios instance with custom SSL settings
const client = axios.create({
httpsAgent: proxyAgent,
timeout: 30000,
validateStatus: function (status) {
return status >= 200 && status < 300;
}
});
// For self-signed certificates
const httpsAgent = new https.Agent({
ca: customCA,
rejectUnauthorized: false
});
client.defaults.httpsAgent = httpsAgent;
async function fetchWithCustomCA(url) {
try {
const response = await client.get(url);
console.log(`Status: ${response.status}`);
console.log(`Response: ${JSON.stringify(response.data, null, 2).slice(0, 100)}...`);
return response.data;
} catch (error) {
console.error('Request failed:', error.message);
return null;
}
}
// Ignore SSL certificate warnings (for development only)
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
Multiple Proxy URLs
const axios = require('axios');
// Multiple SSL proxy configuration
const PROXY_URLS = [
'https://proxy1.example.com:8080',
'https://proxy2.example.com:8080',
'https://proxy3.example.com:8080'
];
const PROXY_USER = "your_proxy_username";
const PROXY_PASS = "your_proxy_password";
// Create proxy agent with round-robin (simple implementation)
let proxyIndex = 0;
function getNextProxy() {
const proxy = PROXY_URLS[proxyIndex];
proxyIndex = (proxyIndex + 1) % PROXY_URLS.length;
return `https://${PROXY_USER}:${PROXY_PASS}@${proxy}`;
}
// Custom adapter for proxy rotation
class ProxyAdapter {
constructor(config) {
this.config = config;
}
async request(config) {
// Set proxy for this request
config.proxy = getNextProxy();
return config;
}
}
// Create axios instance with proxy adapter
const client = axios.create({
adapter: ProxyAdapter,
timeout: 30000
});
async function fetchWithProxyRotation(url) {
try {
const response = await client.get(url);
console.log(`Status: ${response.status} (using proxy: ${client.defaults.proxy})`);
return response.data;
} catch (error) {
console.error('Request failed:', error.message);
return null;
}
}
// Usage example
(async () => {
const result = await fetchWithProxyRotation('https://api.example.com/data');
if (result) {
console.log('Request successful!');
}
})();
Node.js fetch API with SSL Proxy
Basic SSL Proxy Configuration
const https = require('https');
const { HttpsProxyAgent } = require('https-proxy-agent');
// Your SSL proxy configuration
const PROXY_HOST = "192.168.1.100";
const PROXY_PORT = 8080;
const PROXY_USER = "your_proxy_username";
const PROXY_PASS = "your_proxy_password";
// Create proxy agent
const proxyAgent = new HttpsProxyAgent(
`https://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`
);
async function fetchData(url) {
try {
// Create custom HTTPS agent with proxy
const agent = new https.Agent({
proxy: proxyAgent,
keepAlive: true,
keepAliveMsecs: 30000,
maxSockets: 10,
maxFreeSockets: 5
});
const response = await fetch(url, {
agent: agent,
timeout: 30000
});
if (response.ok) {
const data = await response.json();
console.log(`Status: ${response.status}`);
console.log(`Response: ${JSON.stringify(data, null, 2).slice(0, 100)}...`);
return data;
} else {
console.error(`HTTP Error: ${response.status} ${response.statusText}`);
return null;
}
} catch (error) {
console.error('Request failed:', error.message);
return null;
}
}
// Usage example
(async () => {
const result = await fetchData('https://api.example.com/data');
if (result) {
console.log('Request successful!');
}
})();
Fetch with Custom SSL Context
const https = require('https');
const httpsProxyAgent = require('https-proxy-agent');
// SSL proxy configuration
const proxyAgent = new httpsProxyAgent(
`https://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`
);
// Create custom SSL context (for self-signed certificates)
const sslContext = https.createContext({
ca: fs.readFileSync('/path/to/ca-certificate.pem'),
rejectUnauthorized: false
});
async function fetchWithCustomSSL(url) {
try {
const response = await fetch(url, {
agent: proxyAgent,
timeout: 30000
});
// Handle self-signed certificates
if (!response.ok) {
// Try with custom SSL context
const customAgent = new https.Agent({
ca: sslContext.ca,
rejectUnauthorized: false
});
const retryResponse = await fetch(url, {
agent: customAgent,
timeout: 30000
});
if (retryResponse.ok) {
const data = await retryResponse.json();
console.log(`Status: ${retryResponse.status} (custom SSL)`);
console.log(`Response: ${JSON.stringify(data, null, 2).slice(0, 100)}...`);
return data;
}
}
if (response.ok) {
const data = await response.json();
console.log(`Status: ${response.status}`);
console.log(`Response: ${JSON.stringify(data, null, 2).slice(0, 100)}...`);
return data;
} else {
console.error(`HTTP Error: ${response.status} ${response.statusText}`);
return null;
}
} catch (error) {
console.error('Request failed:', error.message);
return null;
}
}
// Usage example
(async () => {
const result = await fetchWithCustomSSL('https://self-signed.badssl.com/');
if (result) {
console.log('Request successful with custom SSL!');
}
})();
Undici (Node.js) with SSL Proxy
Basic SSL Proxy Configuration
const undici = require('undici');
const { ProxyAgent } = require('undici');
// Your SSL proxy configuration
const PROXY_HOST = "192.168.1.100";
const PROXY_PORT = 8080;
const PROXY_USER = "your_proxy_username";
const PROXY_PASS = "your_proxy_password";
// Create proxy dispatcher for undici
const proxyDispatcher = new ProxyAgent(`https://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`);
// Create client with SSL proxy
const client = new undici.Client({
connect: {
dispatcher: proxyDispatcher,
timeout: 30000,
},
});
async function fetchData(url) {
try {
const response = await client.fetch(url);
const body = await response.body.text();
console.log(`Status: ${response.status}`);
console.log(`Response: ${body.slice(0, 100)}...`);
return body;
} catch (error) {
if (error.name === 'ConnectTimeoutError') {
console.error('Connection timeout:', error.message);
} else if (error.name === 'AbortError') {
console.error('Request aborted:', error.message);
} else {
console.error('Request failed:', error.message);
}
return null;
}
}
// Usage example
(async () => {
const result = await fetchData('https://api.example.com/data');
if (result) {
console.log('Request successful!');
}
})();
Undici with Request Headers
const undici = require('undici');
const { ProxyAgent } = require('undici');
// SSL proxy configuration
const PROXY_HOST = "192.168.1.100";
const PROXY_PORT = 8080;
const PROXY_USER = "your_proxy_username";
const PROXY_PASS = "your_proxy_password";
// Create proxy dispatcher
const proxyDispatcher = new ProxyAgent(`https://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`);
const client = new undici.Client({
connect: {
dispatcher: proxyDispatcher,
timeout: 30000,
},
});
async function fetchWithHeaders(url) {
try {
const response = await client.fetch(url, {
method: 'GET',
headers: {
'User-Agent': 'Node.js Proxy Client',
'Accept': 'application/json',
'X-Custom-Header': 'custom-value'
}
});
const body = await response.body.text();
console.log(`Status: ${response.status}`);
console.log(`Headers:`, response.headers);
console.log(`Response: ${body.slice(0, 100)}...`);
return {
status: response.status,
headers: response.headers,
body: body
};
} catch (error) {
console.error('Request failed:', error.message);
return null;
}
}
// Usage example
(async () => {
const result = await fetchWithHeaders('https://api.example.com/data');
if (result) {
console.log('Request successful with headers!');
}
})();
POST Requests with SSL Proxy
const undici = require('undici');
const { ProxyAgent } = require('undici');
// SSL proxy configuration
const PROXY_HOST = "192.168.1.100";
const PROXY_PORT = 8080;
const PROXY_USER = "your_proxy_username";
const PROXY_PASS = "your_proxy_password";
const proxyDispatcher = new ProxyAgent(`https://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`);
const client = new undici.Client({
connect: {
dispatcher: proxyDispatcher,
timeout: 30000,
},
});
async function postData(url, data) {
try {
const response = await client.fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const body = await response.body.text();
const result = JSON.parse(body);
console.log(`Status: ${response.status}`);
console.log(`POST successful: ${JSON.stringify(result, null, 2).slice(0, 100)}...`);
return result;
} catch (error) {
console.error('POST request failed:', error.message);
return null;
}
}
// Usage example
(async () => {
const postData = {
name: 'John Doe',
email: 'john@example.com',
plan: 'premium'
};
const result = await postData('https://api.example.com/users', postData);
if (result) {
console.log('POST request successful!');
}
})();
SSL Proxy Best Practices
1. Always Use HTTPS
Never send credentials or sensitive data over unencrypted connections when using proxies.
2. Use Connection Pooling
Reuse connections for better performance, especially for high-frequency API calls.
3. Handle Timeouts Properly
Set appropriate timeouts to prevent hanging connections, especially with proxy servers.
4. Monitor Performance
Track request times and switch to faster proxies if performance degrades.
5. Use Environment Variables
Store proxy credentials in environment variables, not in code.
Common Issues and Solutions
ECONNRESET or ETIMEDOUT
Solution: Check proxy server connectivity and increase timeout values.
SSL Certificate Errors
Solution: Use system CA certificates or configure custom CA for self-signed certificates.
Proxy Authentication Failures
Solution: Verify proxy credentials and check authentication method requirements.
DNS Resolution Issues
Solution: Ensure proxy server can resolve target domain names or use IP addresses directly.
Ready to Use SSL Proxy in Node.js?
Get your static SSL proxy IPs today and start making secure HTTPS connections with consistent IP addresses for compliance and security requirements.
Get Started with OutboundGatewayRelated SSL Proxy Guides
Python SSL Proxy
Python implementation with requests, urllib3, and aiohttp libraries.
View Python Guide →PHP SSL Proxy
Web-focused proxy configuration with cURL, Guzzle, and Symfony HTTP Client.
View PHP Guide →🚀 Performance Comparison: Node.js excels at concurrent connections and async operations, making it ideal for high-throughput applications. For CPU-intensive tasks, consider Java, or for quick scripting, Python might be more suitable.