aiohttp-middlewares is a collection of useful middlewares for aiohttp applications, providing common web-development needs like error handling, CORS, timeout, and shielding view handlers. The library is currently at version 2.4.0 and maintains a regular monthly release cadence.
Install & Compatibility
Where this runs
tested against v2.4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.701s · 27.3MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 3.9s · import 0.636s · 29MB
27MB installed
● package 27MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
cors_middleware
✓ from aiohttp_middlewares import cors_middleware
Imports the CORS middleware factory.
error_middleware
✓ from aiohttp_middlewares import error_middleware
Imports the error handling middleware factory.
timeout_middleware
✓ from aiohttp_middlewares import timeout_middleware
Imports the request timeout middleware factory.
shield_middleware
✓ from aiohttp_middlewares import shield_middleware
Imports the middleware to shield handlers from CancelledError.
https_middleware
✓ from aiohttp_middlewares import https_middleware
Imports the middleware for HTTPS handling behind proxies.
This example demonstrates how to set up an aiohttp application with `cors_middleware` to allow requests from specific origins and `error_middleware` for global exception handling.
from aiohttp import web
from aiohttp_middlewares import (
cors_middleware,
error_middleware,
)
async def handler(request):
return web.Response(text="Hello, aiohttp-middlewares!")
app = web.Application(
middlewares=(
cors_middleware(origins=("http://localhost:8081", "http://127.0.0.1:8081")),
error_middleware(),
)
)
app.router.add_get('/', handler)
if __name__ == '__main__':
web.run_app(app)
Debug
Known issues
breakingIn `v2.1.0`, CORS middleware handling was changed to correctly add CORS headers even if the request results in an `aiohttp.web.HTTPException`. This might alter behavior for applications relying on previous incorrect handling.fixReview existing CORS configurations and error handling logic to ensure compatibility with the updated behavior where CORS headers are always added for HTTPException responses.
affects: >=2.1.0
breakingPython 3.6 support was dropped in `v2.0.0`, and Python 3.7 support was dropped in `v2.3.0`. Applications on older Python versions will fail to install or run.fixUpgrade your Python environment to 3.8 or newer to use `aiohttp-middlewares` version 2.x and above.
affects: >=2.0.0 (for Py3.6), >=2.3.0 (for Py3.7)
breakingVersion `2.0.0` introduced new lower bounds for core dependencies: `aiohttp>=3.8.1,<4.0` and `async-timeout>=4.0.2,<5.0`. Older versions of these dependencies are no longer supported.fixEnsure your project's `aiohttp` and `async-timeout` dependencies meet the new minimum requirements by updating them to `aiohttp>=3.8.1` and `async-timeout>=4.0.2` respectively.
affects: >=2.0.0
gotchaBy default, `cors_middleware` does not allow any origins to access content. You must explicitly configure allowed origins, URLs, or set `allow_all=True` for it to function.fixAlways provide a `origins` tuple or set `allow_all=True` (for insecure setups) when initializing `cors_middleware`. E.g., `cors_middleware(origins=('http://localhost:8081',))`. affects: *
gotchaThe `error_middleware` should generally be placed at the top of your `middlewares` list to catch all exceptions, but specifically *after* `cors_middleware` if both are used, to ensure CORS headers are applied to error responses.fixWhen defining your `aiohttp.web.Application`, ensure the order of middlewares is `middlewares=(cors_middleware(...), error_middleware(...), ...)` if using both.
affects: *
gotcha`timeout_middleware` raises `asyncio.TimeoutError` but does not handle it by itself. To provide custom error pages or logging for timeouts, `error_middleware` must also be used and placed correctly.fixTo gracefully handle `asyncio.TimeoutError` (and other exceptions), include `error_middleware` in your application's middleware chain. The `error_middleware` should be placed before `timeout_middleware` to properly catch timeout errors.
affects: *
Errors
Common errors & fixes
TypeError: 'type' object is not subscriptable
Using type hints like `list[str]` or `dict[str, int]` in Python versions older than 3.9 without `from __future__ import annotations` or `typing.List`.
fixUpgrade to Python 3.9+ or use `from __future__ import annotations` (if on 3.7/3.8) or import from the `typing` module (e.g., `from typing import List, Dict`). Note that aiohttp-middlewares 2.x requires Python 3.8+.
ModuleNotFoundError: No module named 'aiohttp_middlewares.cors_middleware'
Attempting to import a middleware directly from a submodule (e.g., `aiohttp_middlewares.cors`) instead of the top-level `aiohttp_middlewares` package.
fixAlways import middlewares directly from `aiohttp_middlewares`. For example, `from aiohttp_middlewares import cors_middleware` is correct, not `from aiohttp_middlewares.cors import cors_middleware`.
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host ... connection refused
While not directly an `aiohttp-middlewares` error, if `timeout_middleware` or `shield_middleware` are misconfigured, they might mask or prematurely terminate connection attempts, leading to unexpected connection issues or 504 errors.
fixEnsure `timeout_middleware` settings align with your reverse proxy (e.g., Nginx) timeouts to avoid premature timeouts. Test `shield_middleware` with non-idempotent methods (`POST`, `PUT`) as recommended.
RuntimeError: 'Application.middlewares' should be a list of functions
Passing a middleware factory without calling it, or a regular coroutine function without the `@web.middleware` decorator if attempting to use a custom middleware directly.
fixEnsure that if you are using middleware factories (like `cors_middleware()`, `error_middleware()`), you call them when passing to `Application(middlewares=...)`. For custom middlewares, ensure they are decorated with `@web.middleware` and accept `request` and `handler` parameters.
Audit
Dependencies
pythonrequiredRequires Python version >=3.8, <4.0. Python 3.6 and 3.7 support has been dropped in previous major versions.
aiohttprequiredCore dependency for building aiohttp applications. Requires >=3.8.1, <4.0.
async-timeoutrequiredUsed internally, requires >=4.0.2, <5.0.