brotli-asgi is an ASGI middleware that provides Brotli response compression for ASGI applications like Starlette and FastAPI. It offers faster and more dense compression than GZip, making it a drop-in replacement for the GZipMiddleware. As of v1.6.0, it remains actively maintained with periodic updates for dependencies and occasional feature enhancements.
pip install brotli-asgiVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to integrate `BrotliMiddleware` with a FastAPI application. The middleware is added globally, applying Brotli compression to responses that meet the specified criteria (e.g., minimum size). It also configures a gzip fallback for clients that don't support Brotli.
Upgrade to brotli-asgi version 1.4.0 or newer.
Adjust `quality` (e.g., 3-5 for APIs) and `minimum_size` parameters in `BrotliMiddleware`. For static assets, pre-compression with higher quality is often preferred during build processes.
Ensure responses do not prematurely set `Content-Encoding` if `brotli-asgi` is expected to compress them. Maintain an up-to-date Starlette version, preferably >=0.22.0, for robust fallback handling. The 'avoid double encode' fix was in v1.3.0.
Carefully review your middleware stack. Generally, compression middleware should be applied early enough to process responses, but after any middleware that generates or significantly alters the response content. Consult your ASGI framework's documentation for middleware ordering best practices.
Refer to your ASGI framework's documentation on applying middleware to specific routes or mounted applications. For example, in Starlette/FastAPI, you can add middleware to a `Router` or `Mount` instead of the main application object.
Install the package using pip: `pip install brotli-asgi`
Ensure your import statement is `from brotli_asgi import BrotliMiddleware` and that you are using a compatible version of the library. If you suspect a version issue, try upgrading: `pip install --upgrade brotli-asgi`
Try to ensure a clean installation of the core `brotli` library. This might involve: `pip uninstall brotli brotlipy brotlicffi` followed by `pip install brotli brotli-asgi`. If using Conda, consider `conda install brotli` or `pip install brotlicffi` if the issue persists after updating Conda itself.