Proxy Setup for Python, Node.js and Docker

aiohttp Proxy Setup: Authentication and trust_env

Set up an aiohttp HTTP proxy with current authentication syntax, understand trust_env and CONNECT, and diagnose proxy failures with a tested HTTPS example.

By Proxies.sx Team. Reviewed .

For aiohttp 3.14, pass the HTTP proxy URL through proxy= and build Proxy-Authorization with encode_basic_auth. Environment proxy settings require trust_env=True; the default session does not opt in.

In this guide

Run the current authentication example

Install aiohttp==3.14.5 in a Python 3.10-or-newer environment. Our fixture used Python 3.12. Set the proxy environment inputs before running this example. PROXY_SERVER contains only the scheme, host and port; credentials remain separate.

This example sends an HTTPS request through an HTTP proxy. It gives the request a total timeout and consumes the response inside its context manager. The destination must return JSON for response.json(); change that parsing step when your application expects another format.

import asyncio
import os
import ssl
import aiohttp

async def main():
    proxy_headers = {
        "Proxy-Authorization": aiohttp.encode_basic_auth(
            os.environ["PROXY_USERNAME"], os.environ["PROXY_PASSWORD"]
        )
    }
    tls = ssl.create_default_context(cafile=os.environ.get("PROXY_TEST_CA"))
    timeout = aiohttp.ClientTimeout(total=15, connect=5)
    target = os.environ.get("TARGET_URL", "https://api.ipify.org?format=json")
    try:
        async with aiohttp.ClientSession(trust_env=False, timeout=timeout) as session:
            async with session.get(
                target,
                proxy=os.environ["PROXY_SERVER"],
                proxy_headers=proxy_headers,
                ssl=tls,
                allow_redirects=False,
            ) as response:
                response.raise_for_status()
                print(await response.json())
    except (aiohttp.ClientError, asyncio.TimeoutError) as error:
        print("Request failed:", type(error).__name__)
        raise SystemExit(1)

asyncio.run(main())
Download the complete example

Use the authentication API for your installed version

The aiohttp 3.14 proxy reference deprecates proxy_auth and directs users to encode_basic_auth with proxy_headers. Older tutorials commonly use aiohttp.BasicAuth with proxy_auth. Check the version before copying either form.

Keep the generated value in proxy_headers. Adding a proxy password to ordinary destination headers changes where that credential is sent. Base64 encoding in a Basic authentication value is an encoding, not encryption.

A 407 challenge belongs to the proxy authentication exchange. Follow the 407 diagnosis for credential and challenge checks. A destination's 401 response calls for a separate investigation.

Decide whether the session should read the environment

Use ClientSession(trust_env=True) when the process environment should choose the proxy. In that mode, a matching NO_PROXY entry can bypass it. The explicit example above uses trust_env=False so its route does not depend on inherited environment settings.

We confirmed the difference with the same local target: the default session contacted the target directly; opting in sent the request through the fixture proxy; adding an exact destination IP to NO_PROXY restored the direct path. The environment comparison shows how this differs from HTTPX and Node fetch.

If a script works interactively but fails in a worker, check the worker's environment and library version. Editing a terminal's variables does not rewrite the environment of an already-running service.

Keep the proxy protocol and destination protocol separate

For the example, the first connection is to an HTTP proxy. The proxy opens a tunnel to the HTTPS origin using CONNECT, then the client verifies the origin's certificate. Changing http:// to https:// on the proxy URL requests a different kind of proxy listener.

aiohttp documents limitations around HTTPS proxy connections and TLS inside TLS. Validate that combination with the exact Python and aiohttp versions you deploy. This guide's local fixture covers an HTTP proxy carrying an HTTPS destination.

The built-in proxy configuration described here is for HTTP proxies. A socks5:// URL alone does not add a SOCKS connector. If SOCKS is required, evaluate a compatible connector separately or use the documented SOCKS path in the HTTPX guide.

Read failures before adding concurrent work

ObservationNext step
Proxy connection or CONNECT failureCheck listener scheme, port and proxy credentials before changing destination headers.
Certificate errorCheck the destination name and trusted CA bundle. Keep verification enabled.
JSON parsing failureInspect response status and content type. An HTML response is not the JSON result the example expects.
Timeout under loadSeparate time spent waiting for a connection from network transfer; reduce the workload while investigating.

The client reference defines session, timeout and connector options. Reuse a session for a bounded batch, and close it after the batch finishes. Parallel requests alone do not create independent proxy sessions or unique IPs.

Our local test record covers authenticated CONNECT, rejected credentials and environment routing. It contains no paid-network or target-success benchmark.

Common questions

Why does aiohttp ignore HTTPS_PROXY?

A default session does not enable environment proxy discovery. Use trust_env=True for environment routing, or pass the proxy explicitly to the request. Check NO_PROXY when environment routing is enabled.

Is the example a proxy rotation test?

No. It checks one request and its response. To assess rotation, choose the intended gateway session mode and observe connections over a suitable interval.

Sources and test scope

Official documentation checked on 14 October 2026. The linked local test records identify the tested versions and limits. The examples do not establish public proxy availability or destination acceptance.

Machine-readable guide index and local routing test results.

Connect your application to Proxies.sx

Use the username builder for gateway routing fields and the format converter for existing connection lists. Review Pool Gateway documentation, then check current mobile stock before buying traffic.

For agent-driven workflows, the agent service index lists the supported APIs. A configured HTTP client still needs to validate its task's response.

Configure the client that sends your requests

Start with the proxy configuration guide, or open the setup for your runtime.