skip to content

What do FastAPI's bundled GZipMiddleware, TrustedHostMiddleware and HTTPSRedirectMiddleware each do, and which of their defaults matter when you add them?

level: middleimportance: should knowfreq 25%

answer

  1. re-exported from Starlette
  2. a size floor for compression
  3. Host header checked against a list
  4. 400 for a bad host
  5. 307 to the secure scheme

basics

~20 s

GZipMiddleware compresses responses for clients accepting gzip, skipping bodies under 500 bytes; TrustedHostMiddleware answers 400 to a Host matching no allowed_hosts entry; HTTPSRedirectMiddleware redirects http and ws requests to https and wss with a 307.

solid answer

~30 s

All three are Starlette classes re-exported from `fastapi.middleware`. `GZipMiddleware` compresses when `Accept-Encoding` contains `gzip`, with `minimum_size=500` bytes and `compresslevel=9`; it skips responses that already have `Content-Encoding`, 206 partial responses and excluded types, `text/event-stream` among them. `TrustedHostMiddleware(allowed_hosts=[...])` accepts exact hosts or `*.example.com` patterns and answers `400 Invalid host header` otherwise; without `allowed_hosts` it allows everything, and `www_redirect=True` sends a bare-domain request to the listed `www.` host. It matters because Starlette builds `request.url` and `url_for()` from the Host header. `HTTPSRedirectMiddleware` has no options and answers any `http` or `ws` request with a 307 to `https` or `wss`.

code

python · 21 lines
python
from fastapi import FastAPI
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()

app.add_middleware(GZipMiddleware, minimum_size=500, compresslevel=6)
app.add_middleware(  # added last: outermost, so bad hosts are refused first
    TrustedHostMiddleware,
    allowed_hosts=["api.example.com", "*.api.example.com"],
)


@app.get("/report")
async def report() -> dict[str, str]:
    return {"body": "x" * 2000}


@app.get("/ping")
async def ping() -> dict[str, str]:
    return {"ping": "pong"}

go deeper

for a junior

Know the three classes in fastapi.middleware and in one line each what they do: compress, check the Host header, redirect to https.

for a middle

Explain the defaults: minimum_size 500, compresslevel 9, excluded event streams, 400 Invalid host header, www_redirect True, and the 307 redirect.

for a senior

Connect TrustedHostMiddleware to forged Host headers in url_for() links, and spot the redirect loop HTTPSRedirectMiddleware causes behind TLS termination.

for a principal

Decide which of these duties the app owns and which the edge owns, so compression, host checks and redirects happen once, in one place.

## Where they come from `fastapi.middleware` re-exports Starlette's middleware for convenience: `fastapi.middleware.gzip.GZipMiddleware`, `fastapi.middleware.trustedhost.TrustedHostMiddleware`, `fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware` (and `CORSMiddleware`). They are the same classes as the `starlette.middleware.*` ones, added with `app.add_middleware(Class, **options)`. All three are written as pure ASGI middleware. ## GZipMiddleware It compresses a response when the request's `Accept-Encoding` header contains `"gzip"`, and it handles both ordinary and streaming responses. | Argument | Default | Effect | |---|---|---| | `minimum_size` | `500` | bodies smaller than this many bytes are sent uncompressed | | `compresslevel` | `9` | 1 is fastest with larger output, 9 smallest and slowest | | `thread_minimum_size` | `131072` (128 KiB) | body chunks this large are compressed in a worker thread | | `exclude_content_types` | `DEFAULT_EXCLUDED_CONTENT_TYPES` | media types never compressed | It leaves a response alone when: - the response already has a `Content-Encoding` header (no double encoding); - the status is `206 Partial Content`, to keep range requests correct; - its media type is excluded: by default `text/event-stream` (so Server-Sent Events are not buffered) and already-compressed formats such as zip and gzip archives, common image types, `audio/*`, `video/*` and WOFF fonts. When a response can be compressed it adds `Vary: Accept-Encoding`. On streaming responses it compresses and flushes per chunk, so many tiny chunks compress poorly. The high default `compresslevel` trades CPU for size; a busy JSON API may prefer a lower level. ## TrustedHostMiddleware It checks the `Host` header of HTTP and WebSocket requests against `allowed_hosts`: 1. Exact names (`"api.example.com"`) and subdomain wildcards (`"*.example.com"`) are accepted; a `*` anywhere but the leading `*.` fails an assertion when the middleware is built. 2. A request whose host matches nothing gets `400` with the body `Invalid host header`, except in the `www` case below. 3. `www_redirect` defaults to `True`: if `"www.example.com"` is allowed and a request arrives for `example.com`, it gets a 307 redirect to the `www.` host. 4. Leaving `allowed_hosts` out means `["*"]`, which allows every host, so adding the class without the argument protects nothing. Why it matters: Starlette builds `request.url`, `request.base_url` and `request.url_for()` from the request's `Host` header. Without a check, a client can send a forged host and get your app to produce absolute links that point elsewhere, for example inside a password-reset email or a cached page. Pinning the accepted hosts closes that path in the app; a reverse proxy that only forwards known hosts closes it at the edge too. ## HTTPSRedirectMiddleware It takes no options. Any request whose ASGI scope scheme is `http` or `ws` gets a `307` redirect to the same URL on `https` or `wss`, dropping an explicit port 80 or 443. A 307 keeps the method and body, so a redirected `POST` stays a `POST`. Behind a reverse proxy that terminates TLS, the app sees `http` unless the server is told to trust forwarded headers, and this middleware then redirects forever. Configuring that trust is part of proxy setup, not of this middleware. ## Why these are middleware, not dependencies A dependency runs only for the path operations that declare it, after a route has matched. These three must act on **every** request, including ones no route matches, and two of them change or replace the response itself. That is what app-level middleware is for, and why all three ship as middleware classes. ## Choosing and ordering them - Add `TrustedHostMiddleware` when the app builds absolute URLs or serves several hostnames, with an explicit list. - Add `GZipMiddleware` when nothing in front of the app already compresses; compressing twice is skipped thanks to the `Content-Encoding` check, but compressing in both places wastes CPU. - Add `HTTPSRedirectMiddleware` only when the app itself sees the original scheme; otherwise redirect at the edge. - Register `TrustedHostMiddleware` after the others so it is outermost and refuses a bad host before any other work. ## Checking them in place Three quick checks confirm a configuration does what you think: 1. A request with a `Host` value outside the list should get `400 Invalid host header`; one for a listed subdomain should pass. 2. A request with `Accept-Encoding: gzip` for a body above `minimum_size` should come back with `Content-Encoding: gzip` and `Vary: Accept-Encoding`; a small body should not be compressed. 3. A plain `http` request should get a `307` whose `Location` uses `https`, and a request that already arrives as `https` should pass straight through.

  • Why do FastAPI Server-Sent Events not get gzipped by GZipMiddleware?
    `text/event-stream` is in `DEFAULT_EXCLUDED_CONTENT_TYPES`, so the middleware sends those responses unchanged and events reach the client exactly as the app emits them. If you pass your own `exclude_content_types`, extend the default tuple rather than replace it, or the event stream becomes eligible for compression again.
  • What does TrustedHostMiddleware do with a request for example.com when only www.example.com is allowed in FastAPI?
    With the default `www_redirect=True`, it answers with a 307 redirect to the same URL on `www.example.com`. With `www_redirect=False`, the bare domain is not in the list, so it answers `400 Invalid host header`. List both names if both should be served directly.

  • Adds TrustedHostMiddleware without allowed_hosts and assumes it protects anything.
  • Thinks GZipMiddleware compresses every response, however small.
  • Expects HTTPSRedirectMiddleware to work unchanged behind a TLS-terminating proxy.
  • Believes TrustedHostMiddleware rejects bad hosts with 403.
  • Says HTTPSRedirectMiddleware answers with a 301 that turns POST into GET.

Assumes FastAPI 0.143 on Starlette 1.7; FastAPI accepts Starlette from 0.46, and GZipMiddleware's thread_minimum_size and exclude_content_types exist only in recent Starlette releases.