]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Document how to configure CORSMiddleware globally (#2885)
authortimothy <53824764+timothy-jeong@users.noreply.github.com>
Tue, 4 Mar 2025 00:15:15 +0000 (09:15 +0900)
committerGitHub <noreply@github.com>
Tue, 4 Mar 2025 00:15:15 +0000 (18:15 -0600)
docs/middleware.md

index 27527d2955d9f14884f57ff65dfe1d33f5bf8cf8..01d0afcfbd147424cfcf70ad66a69fc37edb133b 100644 (file)
@@ -92,6 +92,31 @@ appropriate CORS headers, and either a 200 or 400 response for informational pur
 Any request with an `Origin` header. In this case the middleware will pass the
 request through as normal, but will include appropriate CORS headers on the response.
 
+### CORSMiddleware Global Enforcement
+
+When using CORSMiddleware with your Starlette application, it's important to ensure that CORS headers are applied even to error responses generated by unhandled exceptions. The recommended solution is to wrap the entire Starlette application with CORSMiddleware. This approach guarantees that even if an exception is caught by ServerErrorMiddleware (or other outer error-handling middleware), the response will still include the proper `Access-Control-Allow-Origin` header.
+
+For example, instead of adding CORSMiddleware as an inner `middleware` via the Starlette middleware parameter, you can wrap your application as follows:
+
+```python
+from starlette.applications import Starlette
+from starlette.middleware.cors import CORSMiddleware
+
+import uvicorn
+
+app = Starlette()
+app = CORSMiddleware(app=app, allow_origins=["*"])
+
+# ... your routes and middleware configuration ...
+
+if __name__ == '__main__':
+    uvicorn.run(
+        app,
+        host='0.0.0.0',
+        port=8000
+    )
+```
+
 ## SessionMiddleware
 
 Adds signed cookie-based HTTP sessions. Session information is readable but not modifiable.