{"id":6966,"library":"aiohttp-middlewares","title":"aiohttp-middlewares","description":"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.","status":"active","version":"2.4.0","language":"en","source_language":"en","source_url":"https://github.com/playpauseandstop/aiohttp-middlewares","tags":["aiohttp","middleware","web","async","http","cors","error-handling","timeout","security"],"install":[{"cmd":"pip install aiohttp-middlewares","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Requires Python version >=3.8, <4.0. Python 3.6 and 3.7 support has been dropped in previous major versions.","package":"python","optional":false},{"reason":"Core dependency for building aiohttp applications. Requires >=3.8.1, <4.0.","package":"aiohttp","optional":false},{"reason":"Used internally, requires >=4.0.2, <5.0.","package":"async-timeout","optional":false}],"imports":[{"note":"Imports the CORS middleware factory.","symbol":"cors_middleware","correct":"from aiohttp_middlewares import cors_middleware"},{"note":"Imports the error handling middleware factory.","symbol":"error_middleware","correct":"from aiohttp_middlewares import error_middleware"},{"note":"Imports the request timeout middleware factory.","symbol":"timeout_middleware","correct":"from aiohttp_middlewares import timeout_middleware"},{"note":"Imports the middleware to shield handlers from CancelledError.","symbol":"shield_middleware","correct":"from aiohttp_middlewares import shield_middleware"},{"note":"Imports the middleware for HTTPS handling behind proxies.","symbol":"https_middleware","correct":"from aiohttp_middlewares import https_middleware"}],"quickstart":{"code":"from aiohttp import web\nfrom aiohttp_middlewares import (\n    cors_middleware,\n    error_middleware,\n)\n\nasync def handler(request):\n    return web.Response(text=\"Hello, aiohttp-middlewares!\")\n\napp = web.Application(\n    middlewares=(\n        cors_middleware(origins=(\"http://localhost:8081\", \"http://127.0.0.1:8081\")),\n        error_middleware(),\n    )\n)\n\napp.router.add_get('/', handler)\n\nif __name__ == '__main__':\n    web.run_app(app)","lang":"python","description":"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."},"warnings":[{"fix":"Review existing CORS configurations and error handling logic to ensure compatibility with the updated behavior where CORS headers are always added for HTTPException responses.","message":"In `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.","severity":"breaking","affected_versions":">=2.1.0"},{"fix":"Upgrade your Python environment to 3.8 or newer to use `aiohttp-middlewares` version 2.x and above.","message":"Python 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.","severity":"breaking","affected_versions":">=2.0.0 (for Py3.6), >=2.3.0 (for Py3.7)"},{"fix":"Ensure 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.","message":"Version `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.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always provide a `origins` tuple or set `allow_all=True` (for insecure setups) when initializing `cors_middleware`. E.g., `cors_middleware(origins=('http://localhost:8081',))`.","message":"By 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.","severity":"gotcha","affected_versions":"*"},{"fix":"When defining your `aiohttp.web.Application`, ensure the order of middlewares is `middlewares=(cors_middleware(...), error_middleware(...), ...)` if using both.","message":"The `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.","severity":"gotcha","affected_versions":"*"},{"fix":"To 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.","message":"`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.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Upgrade 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+.","cause":"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`.","error":"TypeError: 'type' object is not subscriptable"},{"fix":"Always import middlewares directly from `aiohttp_middlewares`. For example, `from aiohttp_middlewares import cors_middleware` is correct, not `from aiohttp_middlewares.cors import cors_middleware`.","cause":"Attempting to import a middleware directly from a submodule (e.g., `aiohttp_middlewares.cors`) instead of the top-level `aiohttp_middlewares` package.","error":"ModuleNotFoundError: No module named 'aiohttp_middlewares.cors_middleware'"},{"fix":"Ensure `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.","cause":"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.","error":"aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host ... connection refused"},{"fix":"Ensure 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.","cause":"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.","error":"RuntimeError: 'Application.middlewares' should be a list of functions"}]}