Introducing a new way to review your PRs.

Read the announcement

aio-libs / aiohttp

Asynchronous HTTP client/server framework for asyncio and Python

View on GitHub

19 documents · Updated Nov 23, 2026

docs / client-state-and-interception

Client cookies, middleware, and tracing

The client session keeps request state, allows request interception, and exposes hooks for observing request work. A cookie jar carries server state between requests. Middleware can change or retry a request before it reaches the network. Trace signals report request, connection, DNS, and data events to monitoring code. See HTTP client for the wider client model, client request lifecycle for the main request path, client connectivity and proxies for network setup, cookies, compression, and utilities for related shared helpers, and observability and test support for monitoring support.

The session cookie jar is shared state for cookies accepted from responses and selected for later requests. It applies domain, path, secure, host-only, and expiry rules so that a request receives only cookies allowed for its URL. Host-only status is tied to a cookie's domain, path, and name. This identity keeps expiry cleanup and later replacement from leaving a stale host-only marker (aiohttp/cookiejar.py• L44-45, aiohttp/cookiejar.py• L234-329, aiohttp/cookiejar.py• L331-430, aiohttp/cookiejar.py• L432-519). Response processing keeps raw Set-Cookie headers separate so duplicate cookie names are not lost (aiohttp/client.py• L755-759, aiohttp/cookiejar.py• L331-342).

The built-in jar also bounds cookie storage and request headers. It removes expired cookies first, then evicts older cookies when a domain or the whole jar reaches its limit. Domain eviction prefers non-secure cookies and can refuse a new non-secure cookie when only secure cookies remain. When a request has too many cookies or a header that is too large, it keeps the most specific cookies first so a host's own state has priority (aiohttp/cookiejar.py• L389-443, aiohttp/cookiejar.py• L617-740).

The session can start with a custom jar or with the default CookieJar. A caller can also disable cookie processing with DummyCookieJar. Request-level cookies are filtered in a temporary jar, then merged into the cookies selected from the session jar. This keeps one request's additions separate from shared session state (aiohttp/client.py• L379-384, aiohttp/client.py• L646-656, aiohttp/cookiejar.py• L331-342, aiohttp/cookiejar.py• L432-519).

The cookie flow connects response headers to future request headers:

flowchart LR
    R[Response Set-Cookie headers] --> J[Session cookie jar]
    U[Request URL] --> F[Cookie filtering]
    J --> F
    C[Request-level cookies] --> T[Temporary jar]
    T --> F
    F --> H[Cookie request header]
    H --> S[Network request]

Cookie persistence saves the jar as JSON and restores it through the same acceptance rules. The saved form keeps host-only status for each cookie identity and stores an absolute expiry time. New files use restricted permissions because cookies can contain session or authentication tokens (aiohttp/cookiejar.py• L140-232).

The jar rejects cookies from IP hosts unless unsafe mode is enabled. Secure cookies are withheld from non-secure URLs, including shared cookies, unless the origin is listed in treat_as_secure_origin. Expired cookies are removed when the jar is read or updated. A non-positive Max-Age expires a cookie at once, while a very large positive value is capped before time arithmetic. Cookie values that cannot be safely written to a Cookie header are rejected before storage (aiohttp/cookiejar.py• L82-115, aiohttp/cookiejar.py• L283-367, aiohttp/cookiejar.py• L451-615, aiohttp/cookiejar.py• L617-748).

References: aiohttp/client.py• L379-384 aiohttp/client.py• L646-656 aiohttp/client.py• L755-759 aiohttp/cookiejar.py• L44-45 aiohttp/cookiejar.py• L82-115 aiohttp/cookiejar.py• L140-232 aiohttp/cookiejar.py• L234-329 aiohttp/cookiejar.py• L331-430 aiohttp/cookiejar.py• L389-443 aiohttp/cookiejar.py• L451-615 aiohttp/cookiejar.py• L617-748

Cookie parsing turns response and request header text into cookie objects without losing the value format sent by a server. The parser accepts common real-world variations while treating cookie headers as name-value pairs rather than as attribute lists (aiohttp/_cookie_helpers.py• L167-263, aiohttp/_cookie_helpers.py• L266-284). Raw response headers are parsed as a sequence, so each Set-Cookie line can update the jar independently (aiohttp/cookiejar.py• L335-342).

When a request already has a Cookie header, session and request cookies are merged into it. The result is emitted as one header, and coded cookie values can remain unchanged so strict servers do not see an unexpected re-encoding (aiohttp/client_reqrep.py• L1192-1207, aiohttp/_cookie_helpers.py• L85-119).

The public cookie update path copies caller-owned morsels before it normalizes and stores them. This prevents later changes to a caller's cookie object from changing the jar. Raw headers use freshly parsed morsels and can enter the same normalization path without that extra copy (aiohttp/cookiejar.py• L331-365).

References: aiohttp/_cookie_helpers.py• L85-119 aiohttp/_cookie_helpers.py• L167-284 aiohttp/client_reqrep.py• L381-404 aiohttp/client_reqrep.py• L565-568 aiohttp/client_reqrep.py• L1192-1207 aiohttp/cookiejar.py• L331-365 aiohttp/cookiejar.py• L451-472 aiohttp/cookiejar.py• L742-780

Client middleware chain

Client middleware is an async wrapper around the handler that sends a request and returns its response. Session middleware applies by default. Per-request middleware replaces the session list for that request, so callers can select a different interception policy without changing shared session state (aiohttp/client.py• L713-723, aiohttp/client_middlewares.py• L10-16).

The list order defines nesting. The first middleware in the list runs before the next middleware and the network handler. A middleware can change the request, inspect the response, stop the chain, or call the handler more than once. This makes the chain suitable for cross-cutting work such as headers, retries, token refresh, and authentication (aiohttp/client_middlewares.py• L19-55).

The middleware chain surrounds the network send, while cookie selection and request creation happen before the chain. A middleware therefore receives a prepared request with the session's selected cookies. It can still change request headers or perform a controlled retry before the response returns (aiohttp/client.py• L646-710, aiohttp/client.py• L713-726).

Middleware can use the originating client session when it needs to make a related request. If it replaces a request body, it must use the request's body update path so the old body can close and the transfer headers can follow the new body (aiohttp/client_reqrep.py• L1163-1171, aiohttp/client_reqrep.py• L1295-1372).

sequenceDiagram
    participant C as Caller
    participant S as Client session
    participant M1 as First middleware
    participant M2 as Next middleware
    participant N as Network handler
    participant R as Response
    C->>S: Start request
    S->>M1: Prepared request
    M1->>M2: Call next handler
    M2->>N: Call network handler
    N-->>M2: Response
    M2-->>M1: Response or retry
    M1-->>R: Final response
    R-->>C: Return response

References: aiohttp/client.py• L646-710 aiohttp/client.py• L713-726 aiohttp/client_middlewares.py• L10-16 aiohttp/client_middlewares.py• L19-58 aiohttp/client_reqrep.py• L1163-1171 aiohttp/client_reqrep.py• L1295-1372

Digest authentication middleware

Digest authentication middleware handles a server challenge without exposing the password in the request. It sends the request through the chain, reads a 401 Digest challenge, computes an RFC 7616 response, and retries once with an Authorization header. It parses the first challenge without allowing later authentication schemes to replace its fields (aiohttp/client_middleware_digest_auth.py• L111-150, aiohttp/client_middleware_digest_auth.py• L153-191, aiohttp/client_middleware_digest_auth.py• L406-465, aiohttp/client_middleware_digest_auth.py• L467-504).

The middleware can authenticate preemptively after it has learned a challenge. It tracks the challenge, nonce count, and protection space. Credentials are tied to the first request origin and are not sent to another origin unless the challenge declares that URL space as protected. A malformed challenge is passed through without a retry, while missing or unsupported digest values fail when the middleware tries to build authorization (aiohttp/client_middleware_digest_auth.py• L193-219, aiohttp/client_middleware_digest_auth.py• L221-384, aiohttp/client_middleware_digest_auth.py• L386-465, aiohttp/client_middleware_digest_auth.py• L467-504).

The supported protection choices include the standard MD5 and SHA family algorithms plus auth and auth-int quality-of-protection modes. The latter includes the request body in the digest, so a retry must still have access to the body (aiohttp/client_middleware_digest_auth.py• L36-50, aiohttp/client_middleware_digest_auth.py• L274-316).

sequenceDiagram
    participant M as Digest middleware
    participant H as Next handler
    participant W as Server
    M->>H: Request without learned challenge
    H->>W: Request
    W-->>H: 401 Digest challenge
    H-->>M: Challenge response
    M->>M: Build digest authorization
    M->>H: Retry with Authorization
    H->>W: Authenticated request
    W-->>H: Final response
    H-->>M: Final response

References: aiohttp/client_middleware_digest_auth.py• L26-50 aiohttp/client_middleware_digest_auth.py• L101-150 aiohttp/client_middleware_digest_auth.py• L153-219 aiohttp/client_middleware_digest_auth.py• L221-384 aiohttp/client_middleware_digest_auth.py• L386-465 aiohttp/client_middleware_digest_auth.py• L467-504

Request tracing hooks

Tracing is an async signal interface for observing one client request across its full network work. A TraceConfig groups callbacks and creates one trace context for each request, so monitoring code can keep timing or correlation data without changing the request result (aiohttp/tracing.py• L44-105, aiohttp/client.py• L591-601).

The hooks cover the request boundary, request and response data transfer, redirects, connection pool waits, connection creation or reuse, and DNS cache or lookup activity. They receive small parameter objects with the event data. A request can use more than one trace configuration, and each configuration receives the same lifecycle events with its own context (aiohttp/tracing.py• L54-101, aiohttp/tracing.py• L214-330).

The trace points follow the work performed by the client:

StageSignalsMain use
Request boundaryStart, request headers sent, end, exception, redirectRequest timing and outcome
Body transferRequest chunk sent, response chunk receivedUpload and download progress
Connection poolQueued start and end, create start and end, reusePool wait and connection cost
Name lookupResolve start and end, cache hit and missDNS timing and cache behavior

References: aiohttp/tracing.py• L44-123 aiohttp/tracing.py• L214-330

Trace event lifecycle

The session creates trace contexts before request execution and sends the request-start event first. The request object carries the resulting trace objects into the network layer, where request headers and request body chunks are reported as they are sent. Response body events are raised as response bytes move (aiohttp/client.py• L591-601, aiohttp/client_reqrep.py• L559-565, aiohttp/client_reqrep.py• L689-695, aiohttp/client_reqrep.py• L1428-1445, aiohttp/client_reqrep.py• L1544-1561).

Connection and DNS events come from the connector because those operations can wait for a pool slot, reuse an open connection, create a new one, or resolve a host. The session sends a final event after response handling or an exception event during cleanup (aiohttp/connector.py• L660-785, aiohttp/connector.py• L1122-1244, aiohttp/client.py• L862-902).

Trace callbacks are part of the async request path. If a callback raises while a response chunk is reported, the response closes and the error continues to the caller. Monitoring callbacks should therefore keep their work small and handle their own failures when observation must not affect application traffic (aiohttp/client_reqrep.py• L691-697).

References: aiohttp/client.py• L591-601 aiohttp/client.py• L755-766 aiohttp/client.py• L862-902 aiohttp/client_reqrep.py• L559-565 aiohttp/client_reqrep.py• L691-697 aiohttp/client_reqrep.py• L1428-1445 aiohttp/client_reqrep.py• L1544-1561 aiohttp/connector.py• L660-785 aiohttp/connector.py• L1122-1244 aiohttp/tracing.py• L333-468

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the cookie acceptance rules aligned with request cookie filtering. A change to domain, path, secure, host-only, or expiry handling can change which credentials reach a server.
  • Keep treat_as_secure_origin aligned with secure-cookie filtering for both shared and domain-scoped cookies. A change in one path can expose or hide cookies unexpectedly.
  • Keep host-only identity aligned across setting, replacement, expiry cleanup, filtering, and persistence. The cookie name and path are part of the identity.
  • Keep response cookie parsing aligned with raw Set-Cookie header collection. Parsing only a combined header can lose duplicate cookies.
  • Preserve the distinction between caller-owned cookie objects and freshly parsed response cookies. Changes to update paths must not reintroduce shared mutable state.
  • Preserve safe Max-Age handling for zero, negative, and very large values. Expiry arithmetic must not overflow or leave stale cookie state.
  • Keep cookie storage and request-header limits aligned with eviction order and specificity order. A limit change can silently remove state or omit cookies from a request.
  • Preserve middleware list order and the distinction between session-level and per-request middleware. Both affect which policy sees a request first.
  • If digest challenge fields or retry rules change, review origin and protection-space limits together with request-body replay and body-update behavior.
  • If a trace signal changes, update its parameter contract and every lifecycle point that emits it. Request, connector, and request-body events form one observation path.

Important failure modes

TriggerConsequenceGuard
A secure cookie is used on a non-secure URL without an explicit secure-origin exceptionThe cookie is not sentUse HTTPS or configure the intended treat_as_secure_origin entry explicitly
A cookie from an IP host is accepted without unsafe modeThe cookie jar ignores itUse a host name or enable unsafe cookie handling only when required
A caller mutates a cookie object after passing it to the public update pathStored cookie state can diverge from the caller's intended snapshotLet the jar copy caller-owned morsels before normalization
A host-only cookie expires while its identity is tracked without its pathA later cookie at another path can inherit incorrect host-only stateTrack host-only status by domain, path, and name
A non-positive or extremely large Max-Age reaches unsafe time arithmeticThe cookie may expire at the wrong time or trigger an overflowTreat non-positive values as immediate expiry and cap positive values before addition
Cookie storage or the Cookie header exceeds its limitOlder or less specific cookies are evicted or omitted; a new non-secure cookie can be dropped when a full domain contains only secure cookiesKeep the jar's limits and specificity-based selection rules intact
Middleware calls the handler more than once with a non-replayable bodyThe retry can fail or send incomplete dataUse a replayable body and update it through the request body update path when needed
A Digest middleware instance is first used for the wrong originIts credential scope is pinned to that originCreate or first use the middleware for the intended origin
A Digest challenge has no valid parameters or uses an unsupported algorithm or qopA malformed challenge passes through; a challenge with unsupported values fails during authorization creationReturn a supported RFC 7616 challenge or handle the response in another policy
A trace callback raises during response-chunk reportingThe response closes and the callback error reaches the callerKeep observation callbacks failure-safe

Key files

FileWhy to read it
aiohttp/client.pyShows how session cookies, trace contexts, middleware selection, response cookie updates, and request outcomes meet in one request path.
aiohttp/cookiejar.pyDefines the shared cookie state and the rules that control acceptance, persistence, expiry, delivery, storage limits, header limits, host-only identity, secure-origin exceptions, and protection from caller-side mutation.
aiohttp/_cookie_helpers.pyExplains tolerant cookie header parsing and preservation of server-sent cookie encoding.
aiohttp/client_middlewares.pyDefines the middleware contract and the nesting order of the client handler chain.
aiohttp/client_middleware_digest_auth.pyShows the client-side Digest authentication handshake, challenge parsing, and credential scope.
aiohttp/tracing.pyDefines trace configurations, event data, and the request and network observation interface.
aiohttp/client_reqrep.pyConnects cookies, middleware-visible request state, trace hooks, and body transfer to the request and response objects.
aiohttp/connector.pyConnects trace hooks to connection pooling and DNS work.