In a FastAPI app with CORSMiddleware, why does the browser report a CORS error whenever an endpoint raises an unhandled exception, and how do you fix it?
answer
- where the 500 is built
- outermost error layer
- CORS headers never added
- handlers sit inside your middleware
- catch inside, or wrap outside
basics
~20 sAn unhandled exception propagates past CORSMiddleware to ServerErrorMiddleware, which builds the 500 outside every user middleware, so the response has no CORS headers and the browser hides it. Catch errors in a middleware inside CORSMiddleware, or wrap the whole app.
solid answer
~40 sFastAPI's stack is `ServerErrorMiddleware`, then user middleware such as `CORSMiddleware`, then `ExceptionMiddleware`, then the router. An `HTTPException` or validation error is turned into a response by `ExceptionMiddleware`, inside CORS, so it gets CORS headers. An unhandled exception escapes all of them; `ServerErrorMiddleware` then sends `Internal Server Error` (or your `@app.exception_handler(Exception)` response) from outside, without `Access-Control-Allow-Origin`, and the browser reports a CORS failure that hides the 500. The same layout explains why an `HTTPException` raised in a middleware's own code becomes a 500. Fixes: a catch-all middleware registered before `CORSMiddleware` that logs and returns a `JSONResponse` 500, or serving `CORSMiddleware(app=...)` around the whole app.
code
python · 32 linesimport logging
from collections.abc import Awaitable, Callable
from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
logger = logging.getLogger("app")
app = FastAPI()
@app.middleware("http") # added first, so it sits inside CORSMiddleware
async def catch_unhandled(
request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response:
try:
return await call_next(request)
except Exception:
logger.exception("unhandled error on %s", request.url.path)
return JSONResponse({"detail": "Internal Server Error"}, status_code=500)
app.add_middleware( # added last, so it is the outermost user middleware
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_credentials=True,
)
@app.get("/report")
async def report() -> dict[str, str]:
raise RuntimeError("bug")go deeper
Remember that a CORS error in the console can hide a 500; check the status code and the server log before touching CORS settings.
Explain the stack: ServerErrorMiddleware outside, CORSMiddleware in the middle, ExceptionMiddleware inside, and which responses each layer builds.
Diagnose from the status code, choose between a catch-all middleware inside CORS and wrapping the app, and keep exception logging working.
Make error responses part of the API contract so every failure path, crashes included, returns a body and headers clients can read.
## The symptom A frontend on another origin calls a FastAPI API configured with `CORSMiddleware`. Most calls work, including deliberate 404s and 422s. But whenever an endpoint hits a bug, the browser console shows a **CORS error**, not a 500. The server log does show the traceback. The CORS message is misleading: the CORS configuration is fine, and the real problem is where the 500 response is built. ## Where each response is built FastAPI 0.143 assembles its middleware stack like this, outermost first: | Layer | What it produces | |---|---| | `ServerErrorMiddleware` | the 500 for any exception nothing else handled | | user middleware (`CORSMiddleware`, your `@app.middleware("http")` functions) | headers added on the way out | | `ExceptionMiddleware` | responses from `exception_handler`s for `HTTPException`, `RequestValidationError` and other registered types | | router and path operation | normal responses and the 404 or 405 | `CORSMiddleware` adds its headers by watching the response that comes back **through** it. Any response produced **inside** it, by the router or by `ExceptionMiddleware`, gets the headers. A response produced **outside** it does not. ## Following an unhandled exception 1. The path operation raises, say, `RuntimeError`. 2. `ExceptionMiddleware` has no handler for it and lets it propagate. 3. It passes up through `CORSMiddleware`; no response was produced, so there is nothing to add headers to. 4. `ServerErrorMiddleware` catches it and sends a plain-text `500 Internal Server Error`. If you registered `@app.exception_handler(Exception)` or a handler for `500`, FastAPI hands that handler to `ServerErrorMiddleware`, so its response is built at the same outer position. 5. The response has no `Access-Control-Allow-Origin`, so the browser refuses to expose it and reports a CORS error. `ServerErrorMiddleware` re-raises the exception after sending the response, which is why the server still logs the traceback. ## The same layout, from inside a middleware An `HTTPException(status_code=403)` raised **by a middleware's own code**, before or after `call_next`, is outside `ExceptionMiddleware` too. The app's `HTTPException` handler never sees it, and the client gets a 500. A middleware that wants to refuse a request should **return** a response such as `JSONResponse({"detail": "Forbidden"}, status_code=403)` instead of raising, or the check should move into a dependency, where `HTTPException` is handled normally. ## Two fixes - **A catch-all middleware inside CORS.** Register an `@app.middleware("http")` function that wraps `call_next` in `try`/`except Exception`, logs the exception, and returns a `JSONResponse` 500. Register it **before** `CORSMiddleware`; the last added is outermost, so CORS wraps it and decorates the 500 like any other response. Logging is your job now, because the exception no longer reaches `ServerErrorMiddleware`. - **Wrap the whole application.** Starlette's docs suggest serving `CORSMiddleware(app=fastapi_app, ...)` as the ASGI application, so even `ServerErrorMiddleware`'s responses pass through CORS. The server then points at the wrapper, while routes and settings stay on the inner FastAPI object. How to choose between them: - The catch-all middleware keeps `app` a `FastAPI` object and lets you shape the error body, but it only covers what happens inside it; a layer registered after it, or an error in `CORSMiddleware` itself, still escapes. - Wrapping the app covers every response, including `ServerErrorMiddleware`'s own, but the deployment must serve the wrapper, and the default 500 body stays plain text unless you also add a handler. - Either way, keep `debug=False` in production: with `debug=True`, `ServerErrorMiddleware` answers with a traceback page instead of the plain 500. Things that do **not** fix it: - registering `@app.exception_handler(Exception)`, which runs at the outer position; - adding `CORSMiddleware` again or earlier, since a user middleware cannot sit outside `ServerErrorMiddleware`; - loosening `allow_origins`, since the origin was never the problem. ## Diagnosing it quickly Look at the status code of the failed call in the browser's network panel or in the server's access log: a 500 alongside a CORS error points here. The pattern of what works is itself a clue. If 404s, 422s and deliberate `HTTPException` responses reach the frontend with readable bodies while crashes do not, the CORS settings are correct and the missing headers come from the layer that built the response. In tests, an in-process client run with exceptions propagating shows the original traceback directly.
- Does a FastAPI 404 for an unknown path carry the CORS headers?Yes. The 404 is built by the router, inside `CORSMiddleware`, so it passes back out through it and gets `Access-Control-Allow-Origin` for an allowed origin. The same holds for 405 and for 422 validation errors handled by `ExceptionMiddleware`. Responses built outside `CORSMiddleware`, such as the unhandled-exception 500, are the ones that lack them.
- In FastAPI, why does a 403 raised as HTTPException in a middleware turn into a 500?User middleware sits outside `ExceptionMiddleware`, the layer that runs the `HTTPException` handler. An exception raised by the middleware's own code skips that layer and reaches `ServerErrorMiddleware`, which treats it as unhandled and returns 500. Return `JSONResponse(..., status_code=403)` from the middleware, or do the check in a dependency.
- Loosens allow_origins to fix a CORS error that only appears on crashes.
- Expects @app.exception_handler(Exception) responses to pass through CORSMiddleware.
- Raises HTTPException in middleware and expects the app's handler to run.
- Thinks HTTPException responses from endpoints also lose their CORS headers.
- Says user middleware can be placed outside ServerErrorMiddleware.