---
title: "How to Use a Proxy With aiohttp: Async Python and HTTPX"
description: "Pass a proxy to aiohttp with proxy= per request or on ClientSession, add auth, SOCKS5 via aiohttp-socks, limits and timeouts, plus the same in HTTPX."
url: https://proxynet.io/blog/aiohttp-proxy
date: 2026-11-30
author: "Acar Diveroli"
category: "Tutorial, Integration"
lang: en
---

# How to Use a Proxy With aiohttp: Async Python and HTTPX

You moved a script from Requests to aiohttp so that two hundred API calls run at once instead of one after another. The proxy came along as an `HTTPS_PROXY` environment variable, the way it always worked, and the run looks fine until you check an IP-echo service: every request left from your own address. aiohttp ignores proxy environment variables unless you ask it to read them, and it gives no warning when it skips them.

This guide covers every way aiohttp takes a proxy: `proxy=` on a request, the session default added in 3.11, environment variables with `trust_env`, credentials and the 3.14 change to `proxy_auth`, SOCKS5 with `aiohttp-socks`, and how a semaphore, the connector limit and `ClientTimeout` behave under load. A short section does the same in HTTPX. We ran the examples on Python 3.13 with aiohttp 3.13.3 and HTTPX 0.28.1 against a local test proxy that asks for a password and logs every tunnel it opens.

> **Note: Short answer**
>
> Pass the proxy URL on each request with `session.get(url, proxy="http://user:pass@host:port")`, or once for the whole session with `aiohttp.ClientSession(proxy=...)` on aiohttp 3.11 and later. aiohttp reads `HTTP_PROXY` and `HTTPS_PROXY` only when you create the session with `trust_env=True`. The proxy URL starts with `http://` even for HTTPS targets, because aiohttp opens a `CONNECT` tunnel. aiohttp itself speaks only HTTP to a proxy; for SOCKS5, use a `ProxyConnector` from the `aiohttp-socks` package. In HTTPX, write `httpx.AsyncClient(proxy=...)`; the old `proxies=` argument was removed in 0.28.

## How does aiohttp take a proxy?

aiohttp has three places for a proxy, applied in a fixed order: a `proxy=` argument on the request wins, then the session default, then environment variables if `trust_env=True` was set. If none is present, the request goes out directly.

1. **Per request.** `session.get(url, proxy=...)` uses that proxy for one call. It works on every 3.x version.
2. **Session default.** `ClientSession(proxy=...)` sets a proxy for every request of the session. The [aiohttp changelog](https://docs.aiohttp.org/en/stable/changes.html) lists it under 3.11.0, released in November 2024.
3. **Environment.** `ClientSession(trust_env=True)` reads `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY`, and credentials from `~/.netrc`. The default is `False`.

How aiohttp talks to the proxy depends on the target URL. For an `http://` target it sends the full URL to the proxy in an ordinary request. For an `https://` target it first sends `CONNECT host:443`, waits for `200 Connection established`, and then runs TLS with the target inside that tunnel, so the proxy never sees the decrypted request.

## How do you set a proxy for one request?

Pass the proxy URL as the `proxy` argument, with the credentials inside the URL:

```python
import asyncio

import aiohttp

PROXY = "http://user:pass@pr.proxynet.io:8000"

async def main() -> None:
    timeout = aiohttp.ClientTimeout(total=30)
    async with aiohttp.ClientSession(timeout=timeout) as session:
        async with session.get("https://httpbin.org/ip", proxy=PROXY) as resp:
            print(resp.status, await resp.json())

asyncio.run(main())
```

The target is HTTPS and the proxy URL is `http://`, which is correct: the scheme of the proxy URL says how your code reaches the proxy, and the tunnel carries the encryption. Writing `https://` there asks for a TLS connection to the proxy itself, which only an HTTPS proxy understands. Against our plain HTTP test proxy it did not fail fast; the request hung until the 15-second timeout. The aiohttp documentation also warns that TLS inside TLS, an HTTPS target through an HTTPS proxy, may not work on current CPython.

## How do you set one proxy for the whole ClientSession?

From aiohttp 3.11, give the proxy to the session and every request uses it:

```python
async with aiohttp.ClientSession(proxy=PROXY, timeout=timeout) as session:
    for _ in range(3):
        async with session.get("https://httpbin.org/ip") as resp:
            print((await resp.json())["origin"])
```

A `proxy=` on an individual request still overrides the session value, so you can keep a default and make exceptions. One detail matters later for rotation: these three requests produced a single `CONNECT` line in our proxy log, because aiohttp kept the tunnel open and reused it. To support versions older than 3.11, keep `proxy=` on each request.

## How do you pass the proxy username and password?

The way that works on every version is `user:pass@` inside the proxy URL; aiohttp turns it into a `Proxy-Authorization: Basic …` header. Special characters are the catch. In our test a password containing `#` and `/` failed with `InvalidURL` before any connection was made, and the same password passed through `urllib.parse.quote` worked:

```python
import os
from urllib.parse import quote

user = os.environ["PROXY_USER"]
password = quote(os.environ["PROXY_PASS"], safe="")
PROXY = f"http://{user}:{password}@pr.proxynet.io:8000"
```

The separate argument `proxy_auth=aiohttp.BasicAuth("user", "pass")` still works on 3.13, but aiohttp 3.14.0 (June 2026) deprecated `BasicAuth` and `proxy_auth`; they raise a `DeprecationWarning` and are due for removal in 4.0. The replacement in the [aiohttp proxy support guide](https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support) is a header built with `encode_basic_auth()`:

```python
from aiohttp import encode_basic_auth  # aiohttp 3.14 and later

proxy_headers = {"Proxy-Authorization": encode_basic_auth("user", "pass")}
async with session.get(
    "https://httpbin.org/ip",
    proxy="http://pr.proxynet.io:8000",
    proxy_headers=proxy_headers,
) as resp:
    print(await resp.json())
```

`encode_basic_auth` returns the finished `Basic <base64>` string. `proxy_headers` is a request argument; the 3.14.5 `ClientSession` constructor does not accept it, so for a session-wide proxy with credentials, use the URL form. With IP whitelisting on the provider side, the URL needs no credentials at all.

## Does aiohttp read HTTP_PROXY and HTTPS_PROXY?

Only with `trust_env=True`, and this is the difference from Requests that catches people. With `HTTPS_PROXY` set, our session created with `trust_env=True` opened a tunnel through the test proxy, while a default session sent the same request directly and the proxy logged nothing. How Requests treats the same variables is in [How to Use a Proxy With Python Requests](/blog/python-requests-proxy).

```bash
export HTTPS_PROXY="http://user:pass@pr.proxynet.io:8000"
export NO_PROXY="localhost,127.0.0.1"
```

```python
async with aiohttp.ClientSession(trust_env=True) as session:
    async with session.get("https://httpbin.org/ip") as resp:
        print(await resp.json())
```

In PowerShell the first line is `$env:HTTPS_PROXY = "http://user:pass@pr.proxynet.io:8000"`. aiohttp reads the variables through Python's `urllib.request.getproxies()`, so lowercase names such as `https_proxy` work too, and hosts in `NO_PROXY` skip the proxy. An explicit `proxy=` takes priority over the environment.

## How do you use a SOCKS5 proxy with aiohttp?

aiohttp has no SOCKS support of its own; you need a connector from a separate package. The common choice is [aiohttp-socks](https://github.com/romis2012/aiohttp-socks), which handles SOCKS4, SOCKS5 and proxy chains and needs aiohttp 3.10 or later:

```bash
pip install aiohttp-socks
```

```python
import asyncio

import aiohttp
from aiohttp_socks import ProxyConnector

async def main() -> None:
    # rdns is on by default for socks5: the proxy resolves the hostname
    connector = ProxyConnector.from_url("socks5://user:pass@pr.proxynet.io:1080")
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get("https://httpbin.org/ip") as resp:
            print(await resp.json())

asyncio.run(main())
```

The proxy goes into the connector, not into `proxy=`; do not combine the two. A trap we hit: aiohttp does not check the scheme of a `proxy=` URL. When we passed `socks5://user:pass@127.0.0.1:8899` to `proxy=` and pointed it at our HTTP test proxy, the request returned `200` with no error, because aiohttp simply spoke HTTP to that port. Against a real SOCKS5 port the same line fails. For traffic that needs SOCKS5 itself, such as UDP or tools that only speak SOCKS, a [SOCKS5 Proxy](https://proxynet.io/socks5-proxy) with the connector above is the setup.

## What are the ways to give aiohttp a proxy?

| Method | Code | Since |
|---|---|---|
| Per request | `session.get(url, proxy=URL)` | All 3.x |
| Session default | `ClientSession(proxy=URL)` | 3.11 |
| Environment | `ClientSession(trust_env=True)` | All 3.x |
| Header auth | `proxy_headers` + `encode_basic_auth` | 3.14 |
| Auth object | `proxy_auth=BasicAuth(...)` | Deprecated in 3.14 |
| SOCKS5 | `ProxyConnector.from_url(...)` | aiohttp-socks |

## How do you limit concurrency and set timeouts?

Use three controls together: an `asyncio.Semaphore` for how many requests your code starts at once, `TCPConnector(limit=...)` for how many connections the session opens, and `ClientTimeout` for how long one request may take. The defaults, 100 connections and 300 seconds in total, are too generous for a proxy job.

Keep the semaphore even with a connector limit, because a request waiting for a free pooled connection is already on the clock. We sent ten requests, each answered by a local echo server after two seconds, through a session with `TCPConnector(limit=2)` and `ClientTimeout(total=5)`. Six of the ten failed with `TimeoutError` while still queued. With `asyncio.Semaphore(2)` around each request, all ten succeeded in about ten seconds, because a task starts its request, and its timer, only after it gets a slot.

`ClientTimeout` has four fields: `total` for the whole request, `connect` for getting a connection (waiting in the pool included), `sock_connect` for the TCP connection itself, and `sock_read` for the gap between chunks of data. A dead proxy exit shows up quickly with `sock_connect=10`; a target that stalls mid-response raised `SocketTimeoutError` in our test with `sock_read` set.

## How do rotating and sticky proxies behave with aiohttp?

On a rotating gateway the exit IP changes per connection, not per request. A gateway such as our [Rotating Proxy](https://proxynet.io/rotating-proxy) picks a new exit each time a tunnel opens, and aiohttp keeps tunnels open for reuse. In our test, three requests on a default session opened one tunnel; with `TCPConnector(force_close=True)` they opened three.

- **A new IP for every request:** create the connector with `force_close=True`. Each request then pays for a new TCP and TLS handshake.
- **The same IP for a series of requests:** keep the default connector and add a session ID to the username, as in `user-session-a1b2c3-ttl-600`. The gateway holds the exit for that ID for 1 to 60 minutes. The hyphenated username reached our proxy unchanged; it needs no encoding.

How pooled connections share exits across workers is covered in [Web Scraping in Python with Rotating Proxies](/blog/python-web-scraping-rotating-proxy).

## A complete script: check exit IPs concurrently with retries

The script sends ten requests to an IP-echo service through the proxy, at most five at a time, retries network errors and `429` or `5xx` responses with exponential backoff, stops at once on a `407`, and prints how many distinct exit addresses it saw. Run it as a setup check before any real job.

```python
import asyncio
import os
import random
from collections import Counter

import aiohttp

# Read the proxy from the environment so the password stays out of the code
PROXY = os.environ.get("PROXY_URL", "http://user:pass@pr.proxynet.io:8000")
ECHO = os.environ.get("ECHO_URL", "https://api.ipify.org?format=json")
MAX_IN_FLIGHT = 5
ATTEMPTS = 4
RETRY_STATUS = {429, 500, 502, 503, 504}

async def fetch_ip(session: aiohttp.ClientSession, gate: asyncio.Semaphore, n: int) -> str:
    for attempt in range(1, ATTEMPTS + 1):
        try:
            # The timeout clock starts only after a slot is free
            async with gate, session.get(ECHO) as resp:
                if resp.status not in RETRY_STATUS:
                    resp.raise_for_status()
                    data = await resp.json(content_type=None)
                    return data.get("ip") or data.get("origin")
                reason = f"HTTP {resp.status}"
        except aiohttp.ClientHttpProxyError as exc:
            if exc.status == 407:
                raise  # wrong username or password: retrying will not help
            reason = f"proxy returned {exc.status}"
        except (aiohttp.ClientConnectionError, asyncio.TimeoutError) as exc:
            reason = type(exc).__name__
        if attempt == ATTEMPTS:
            raise RuntimeError(f"request {n}: gave up after {ATTEMPTS} attempts ({reason})")
        # Back off outside the semaphore so the slot goes to another task
        await asyncio.sleep(2 ** (attempt - 1) + random.uniform(0, 0.5))
    raise AssertionError("unreachable")

async def main(count: int = 10) -> None:
    timeout = aiohttp.ClientTimeout(total=30, sock_connect=10)
    # force_close: a new connection, and so a new tunnel, for every request
    connector = aiohttp.TCPConnector(limit=MAX_IN_FLIGHT, force_close=True)
    gate = asyncio.Semaphore(MAX_IN_FLIGHT)
    async with aiohttp.ClientSession(proxy=PROXY, timeout=timeout, connector=connector) as session:
        results = await asyncio.gather(
            *(fetch_ip(session, gate, n) for n in range(count)), return_exceptions=True
        )
    ips = Counter(r for r in results if isinstance(r, str))
    errors = [r for r in results if isinstance(r, BaseException)]
    print(f"{sum(ips.values())} ok, {len(errors)} failed, {len(ips)} distinct exit IPs")
    for ip, hits in ips.most_common():
        print(f"  {ip}  x{hits}")
    for err in errors:
        print("  error:", type(err).__name__, str(err).split(", url=")[0])

if __name__ == "__main__":
    asyncio.run(main())
```

Against the local test proxy with correct credentials it printed `10 ok, 0 failed`, the proxy logged ten separate tunnels, and the echo server never saw more than five requests at once. With a wrong password all ten failed with `ClientHttpProxyError` and status `407`, and the proxy logged exactly ten attempts, so nothing was retried. When the proxy answered `502`, every request gave up after four attempts with the reason in the message. Through a local proxy all exits are your own address; through a rotating gateway the distinct count is the number to read.

The backoff sleep sits outside `async with gate`, so a task waiting to retry does not hold a slot. The error line cuts the message at `, url=` because aiohttp's proxy exceptions print the proxy URL with its password; our 407 message contained `user:wrong@127.0.0.1:8899`. Strip it before anything reaches a log.

## Which errors does aiohttp raise with a proxy?

| What happened | What aiohttp raises | First check |
|---|---|---|
| Wrong proxy password, HTTPS target | `ClientHttpProxyError`, `status` 407 | Username, password, encoding |
| Wrong proxy password, HTTP target | No exception; response status 407 | Same as above |
| Proxy host or port unreachable | `ClientProxyConnectionError` | Host, port, firewall |
| Proxy cannot reach the target | Response 502 or 504, or `ClientHttpProxyError` | Retry, then another exit |
| Request took longer than `total` | `asyncio.TimeoutError` | Timeout values, exit speed |
| Target stalled mid-response | `SocketTimeoutError` | `sock_read` value |

The two 407 rows are why one `except` clause is not enough. For an HTTPS target the proxy refuses the `CONNECT`, and aiohttp raises `ClientHttpProxyError`, a subclass of `ClientResponseError` whose `status` holds the code. For a plain HTTP target the refusal arrives as an ordinary response, and nothing is raised unless you call `raise_for_status()`.

## How do you use a proxy with HTTPX AsyncClient?

HTTPX takes the proxy on the client with `proxy=`, and the async client works like the sync one:

```python
import asyncio

import httpx

PROXY = "http://user:pass@pr.proxynet.io:8000"

async def main() -> None:
    async with httpx.AsyncClient(proxy=PROXY, timeout=httpx.Timeout(30, connect=10)) as client:
        resp = await client.get("https://httpbin.org/ip")
        print(resp.status_code, resp.json())

asyncio.run(main())
```

Three differences from aiohttp matter. HTTPX 0.26 deprecated `proxies=` and 0.28 removed it, so older examples fail with `TypeError: AsyncClient.__init__() got an unexpected keyword argument 'proxies'`, exactly what our 0.28.1 install printed. HTTPX reads `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` and `NO_PROXY` by default; `trust_env=False` turns that off. SOCKS needs the `httpx[socks]` extra and a `socks5://` or `socks5h://` URL (`socks5h` is accepted from 0.28); without the extra, our test raised an `ImportError` naming it.

For different proxies per destination, the [HTTPX proxy documentation](https://www.python-httpx.org/advanced/proxies/) uses `mounts=` with one transport per URL pattern, such as `{"https://": httpx.AsyncHTTPTransport(proxy=PROXY)}`. A wrong password on an HTTPS target raised `httpx.ProxyError` with `407 Proxy Authentication Required`, and an unreachable proxy raised `httpx.ConnectError`. Which of the three libraries to pick in the first place is the subject of [HTTPX vs. Requests vs. AIOHTTP](/blog/httpx-vs-requests-vs-aiohttp).

## Where is this setup used?

An async client with a proxy fits jobs where many independent requests leave at once and their origin matters: checking how your own API or storefront answers visitors from different countries, monitoring public price and availability pages at a polite rate, verifying ad redirects per market, and running uptime probes from several regions. The proxy decides which network a request appears from; the semaphore and timeouts decide how hard you press on the target.

## Common mistakes

- **Setting `HTTPS_PROXY` and expecting aiohttp to use it.** Without `trust_env=True` the variable is ignored.
- **Writing `https://` in the proxy URL.** For a normal HTTP proxy it is `http://`; the tunnel handles HTTPS targets.
- **Passing a `socks5://` URL to `proxy=`.** aiohttp neither speaks SOCKS nor rejects the scheme. Use `aiohttp-socks`.
- **Leaving special characters in the password unencoded.** Use `quote(password, safe="")`.
- **Relying on the connector limit alone.** Queued requests time out in the pool; add a semaphore.
- **Expecting a new IP per request with the default connector.** Reused tunnels keep the same exit; use `force_close=True`.
- **Retrying a 407 or logging `str(exc)`.** Wrong credentials stay wrong, and the message contains the password.
- **Using `proxies=` in HTTPX 0.28 or later.** Use `proxy=` or `mounts=`.

## Which setup should you choose?

| Your situation | Use |
|---|---|
| Same proxy for every request, aiohttp 3.11+ | `ClientSession(proxy=URL)` |
| Different proxy per request | `session.get(url, proxy=URL)` |
| Proxy comes from the environment or CI | `ClientSession(trust_env=True)` |
| Password with special characters | `quote(password, safe="")` in the URL |
| aiohttp 3.14+, credentials separate from URL | `proxy_headers` + `encode_basic_auth` |
| SOCKS5 proxy | `aiohttp-socks` `ProxyConnector` |
| New exit IP for every request | Rotating gateway + `force_close=True` |
| Same exit for a series of requests | Sticky session ID in the username |
| Sync and async code in one project | HTTPX with `proxy=` |

## Frequently asked questions

### Does aiohttp ClientSession support a proxy parameter?

Yes, from aiohttp 3.11.0. `ClientSession(proxy="http://user:pass@host:port")` applies the proxy to every request in the session, and a `proxy=` on a single request overrides it. On older versions, pass `proxy=` on each request.

### How do I use an environment variable for the aiohttp proxy?

Create the session with `aiohttp.ClientSession(trust_env=True)`. aiohttp then reads `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` in upper or lower case, and credentials from `~/.netrc`. Without `trust_env=True`, the variables are ignored.

### What is the correct aiohttp proxy URL format?

`http://username:password@host:port`, for example `http://user:pass@pr.proxynet.io:8000`. Keep the `http://` scheme even when the target is HTTPS, and URL-encode characters such as `#`, `/`, `?` and `%` in the password.

### Is there an aiohttp ProxyConnector for SOCKS5?

Not in aiohttp itself. `ProxyConnector` comes from the separate `aiohttp-socks` package: `ProxyConnector.from_url("socks5://user:pass@host:port")`, passed to `ClientSession(connector=...)`. For SOCKS5 it resolves hostnames on the proxy side by default.

### Why does aiohttp show a DeprecationWarning for proxy_auth?

aiohttp 3.14.0 deprecated `BasicAuth` and the `proxy_auth` parameter, with removal planned for 4.0. Put the credentials in the proxy URL, or pass `proxy_headers={"Proxy-Authorization": aiohttp.encode_basic_auth(user, password)}` on the request.

### How many concurrent requests should go through one proxy?

Start with five to ten in flight and raise the number while watching error rates and response times. The right value depends on your provider's connection limit and on how much load the target accepts; a semaphore makes it a single setting.

## Summary

aiohttp takes a proxy through `proxy=` on the request, `ClientSession(proxy=...)` from 3.11, or environment variables only with `trust_env=True`. Keep the proxy URL `http://` for HTTPS targets, encode special characters in the password, and move from `proxy_auth` to `encode_basic_auth` with `proxy_headers` on 3.14. SOCKS5 needs `aiohttp-socks`. Under load, pair a semaphore with the connector limit and `ClientTimeout`, use `force_close=True` when every request needs a new exit, and check the exits against an echo service first. In HTTPX the same setup is `AsyncClient(proxy=...)`. For the exits themselves, a [Residential Proxy](https://proxynet.io/residential-proxy) pool gives each tunnel an ordinary home connection with country and city targeting.
