Skip to content

Commit 708930c

Browse files
Document how to configure CORSMiddleware globally (#2885)
1 parent a404872 commit 708930c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

docs/middleware.md

+25
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,31 @@ appropriate CORS headers, and either a 200 or 400 response for informational pur
9292
Any request with an `Origin` header. In this case the middleware will pass the
9393
request through as normal, but will include appropriate CORS headers on the response.
9494

95+
### CORSMiddleware Global Enforcement
96+
97+
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.
98+
99+
For example, instead of adding CORSMiddleware as an inner `middleware` via the Starlette middleware parameter, you can wrap your application as follows:
100+
101+
```python
102+
from starlette.applications import Starlette
103+
from starlette.middleware.cors import CORSMiddleware
104+
105+
import uvicorn
106+
107+
app = Starlette()
108+
app = CORSMiddleware(app=app, allow_origins=["*"])
109+
110+
# ... your routes and middleware configuration ...
111+
112+
if __name__ == '__main__':
113+
uvicorn.run(
114+
app,
115+
host='0.0.0.0',
116+
port=8000
117+
)
118+
```
119+
95120
## SessionMiddleware
96121

97122
Adds signed cookie-based HTTP sessions. Session information is readable but not modifiable.

0 commit comments

Comments
 (0)