CORS
suggest changeCORS (Cross-Origin Resource Sharing) is a set of HTTP headers that lets a server tell the browser: "JavaScript loaded from this other origin may read my responses".
You run into CORS when a front-end (React, Vue, plain JavaScript) served from one origin calls a Python API on a different origin, for example a Vite dev server on http://localhost:5173 calling a Flask API on http://localhost:5000. The browser blocks the response and the console shows an error like:
Access to fetch at 'http://localhost:5000/api/items' from origin
'http://localhost:5173' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
The fix is always on the server: it has to send the right Access-Control-* headers. This article shows how CORS works and how to configure it in plain http.server, Flask, FastAPI and Django.
Same-origin policy and what an origin is
Browsers enforce the same-origin policy: a script can freely read responses only from its own origin. An origin is the triple (scheme, host, port). The path doesn't matter.
from urllib.parse import urlsplit
DEFAULT_PORTS = {"http": 80, "https": 443}
def origin(url: str) -> tuple[str, str, int]:
parts = urlsplit(url)
port = parts.port or DEFAULT_PORTS[parts.scheme]
return (parts.scheme, parts.hostname, port)
page = "https://app.example.com/dashboard"
for target in [
"https://app.example.com/api/items",
"https://app.example.com:443/api",
"http://app.example.com/api",
"https://api.example.com/items",
"https://app.example.com:8443/api",
]:
same = origin(page) == origin(target)
print(f"{target:38} same-origin={same}")
Output:
https://app.example.com/api/items same-origin=True
https://app.example.com:443/api same-origin=True
http://app.example.com/api same-origin=False
https://api.example.com/items same-origin=False
https://app.example.com:8443/api same-origin=False
A different scheme, subdomain or port makes it a cross-origin request.
Things to keep in mind:
- CORS is enforced only by browsers.
curl,requests,httpxand server-to-server calls ignore it completely. - CORS is not a security feature for your server. It relaxes the browser's same-origin policy. It doesn't stop anyone from calling your API; you still need authentication.
- When a request is blocked, the server often did receive and process it. The browser just hides the response from JavaScript.
Simple requests and preflight requests
For a cross-origin request the browser sends an Origin header and checks the response.
A simple request is a GET, HEAD or POST that uses only basic headers and, for POST, a Content-Type of text/plain, multipart/form-data or application/x-www-form-urlencoded. The browser sends it directly and checks Access-Control-Allow-Origin in the response.
Everything else (PUT, DELETE, PATCH, Content-Type: application/json, an Authorization header, custom headers like X-Api-Key) triggers a preflight: before the real request the browser sends an OPTIONS request asking for permission:
OPTIONS /api/items HTTP/1.1
Origin: http://localhost:5173
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
The server must answer with a 2xx status and headers that allow that origin, method and headers. Only then does the browser send the real POST.
The headers a server can send:
| Header | Meaning |
|---|---|
Access-Control-Allow-Origin |
the allowed origin, or * for any origin |
Access-Control-Allow-Methods |
methods allowed (preflight response) |
Access-Control-Allow-Headers |
request headers allowed (preflight response) |
Access-Control-Allow-Credentials |
true to allow cookies / HTTP auth |
Access-Control-Expose-Headers |
response headers JavaScript may read beyond the basic ones |
Access-Control-Max-Age |
seconds the browser may cache the preflight result |
Vary: Origin |
tells caches that the response depends on the Origin header |
CORS by hand with http.server
Implementing CORS with the standard library shows exactly what the frameworks do for you. The server checks the Origin against an allow-list, echoes it back if it's allowed, and answers OPTIONS preflight requests:
import json
import threading
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
ALLOWED_ORIGINS = {"http://localhost:5173", "https://app.example.com"}
class Handler(BaseHTTPRequestHandler):
def cors_headers(self):
origin = self.headers.get("Origin")
if origin in ALLOWED_ORIGINS:
self.send_header("Access-Control-Allow-Origin", origin)
self.send_header("Vary", "Origin")
def do_OPTIONS(self):
self.send_response(204)
self.cors_headers()
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
self.send_header("Access-Control-Max-Age", "600")
self.end_headers()
def do_GET(self):
body = json.dumps({"message": "hello"}).encode()
self.send_response(200)
self.cors_headers()
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f"http://127.0.0.1:{server.server_port}/api"
def show(method, origin, extra=None):
headers = {"Origin": origin, **(extra or {})}
req = urllib.request.Request(url, method=method, headers=headers)
with urllib.request.urlopen(req) as resp:
print(method, origin, "->", resp.status)
for k, v in resp.headers.items():
if k.startswith("Access-Control") or k == "Vary":
print(f" {k}: {v}")
show("GET", "http://localhost:5173")
show("GET", "https://evil.example")
show("OPTIONS", "https://app.example.com",
{"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "content-type"})
server.shutdown()
Output:
GET http://localhost:5173 -> 200
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin
GET https://evil.example -> 200
Vary: Origin
OPTIONS https://app.example.com -> 204
Access-Control-Allow-Origin: https://app.example.com
Vary: Origin
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600
Notice that the request from https://evil.example still gets a 200 with the data. The server doesn't refuse it; it simply omits Access-Control-Allow-Origin, and the browser then refuses to hand the body to the page.
Access-Control-Allow-Origin accepts only a single origin or *. To allow several origins you must echo the matching one, as above, and add Vary: Origin so a shared cache doesn't serve a response meant for one origin to another.
For more about this module see Basic handling of GET POST PUT using BaseHTTPRequestHandler.
Flask: manual after_request hook
In Flask you can add the headers to every response with an after_request hook. Flask answers OPTIONS automatically for every route, so the hook also covers preflight requests:
from flask import Flask, jsonify, request
app = Flask(__name__)
ALLOWED_ORIGINS = {"http://localhost:5173", "https://app.example.com"}
@app.after_request
def add_cors_headers(response):
origin = request.headers.get("Origin")
if origin in ALLOWED_ORIGINS:
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE"
response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
response.headers["Access-Control-Max-Age"] = "600"
response.vary.add("Origin")
return response
@app.get("/api/items")
def list_items():
return jsonify([{"id": 1, "name": "apple"}])
@app.post("/api/items")
def create_item():
return jsonify(request.get_json()), 201
if __name__ == "__main__":
client = app.test_client()
r = client.options("/api/items", headers={
"Origin": "http://localhost:5173",
"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "content-type",
})
print(r.status_code, ", ".join(sorted(r.headers["Allow"].split(", "))))
print(r.headers["Access-Control-Allow-Origin"])
print(r.headers["Access-Control-Allow-Methods"])
r = client.get("/api/items", headers={"Origin": "https://evil.example"})
print(r.status_code, r.headers.get("Access-Control-Allow-Origin"), r.headers["Vary"])
Output:
200 GET, HEAD, OPTIONS, POST
http://localhost:5173
GET, POST, PUT, DELETE
200 None Origin
The Flask test client is a convenient way to check CORS headers without a browser.
Flask: flask-cors extension
For anything beyond a toy, use the flask-cors extension (pip install flask-cors). It handles preflight, per-route rules, credentials and regular expressions:
from flask import Flask, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(
app,
resources={r"/api/*": {"origins": ["http://localhost:5173", "https://app.example.com"]}},
supports_credentials=True,
max_age=600,
)
@app.get("/api/me")
def me():
return jsonify(user="alice")
@app.get("/public/stats")
@cross_origin() # any origin, for this route only
def stats():
return jsonify(visits=42)
@app.get("/internal")
def internal():
return jsonify(secret=True)
if __name__ == "__main__":
c = app.test_client()
def show(path, origin, method="GET", **hdrs):
r = c.open(path, method=method, headers={"Origin": origin, **hdrs})
print(method, path, r.status_code)
for k, v in r.headers.items():
if k.startswith("Access-Control") or k == "Vary":
print(f" {k}: {v}")
show("/api/me", "https://app.example.com")
show("/api/me", "https://app.example.com", method="OPTIONS",
**{"Access-Control-Request-Method": "DELETE",
"Access-Control-Request-Headers": "authorization"})
show("/api/me", "https://evil.example")
show("/public/stats", "https://anyone.example")
show("/internal", "https://app.example.com")
Output:
GET /api/me 200
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Vary: Origin
OPTIONS /api/me 200
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization
Access-Control-Max-Age: 600
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Vary: Origin
GET /api/me 200
GET /public/stats 200
Access-Control-Allow-Origin: https://anyone.example
Vary: Origin
GET /internal 200
resourcesmaps URL regexes to options, so/internalgets no CORS headers at all.originsaccepts strings, compiled regexes or"*".- by default flask-cors echoes back requested headers and allows all common methods; restrict them with
allow_headers=andmethods= expose_headers=["X-Total-Count"]lets JavaScript read custom response headers
FastAPI and Starlette: CORSMiddleware
FastAPI re-exports Starlette's CORSMiddleware. Add it once to the application:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "https://app.example.com"],
allow_origin_regex=r"https://.*\.preview\.example\.com",
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
expose_headers=["X-Total-Count"],
max_age=600,
)
@app.get("/api/items")
def list_items():
return [{"id": 1, "name": "apple"}]
Testing it with TestClient (needs pip install httpx2; older Starlette versions use httpx):
from fastapi.testclient import TestClient
client = TestClient(app)
def preflight(origin, method, req_headers=None):
headers = {"Origin": origin, "Access-Control-Request-Method": method}
if req_headers:
headers["Access-Control-Request-Headers"] = req_headers
r = client.options("/api/items", headers=headers)
print(origin, method, "->", r.status_code, r.text)
print(" allow-origin:", r.headers.get("access-control-allow-origin"))
r = client.get("/api/items", headers={"Origin": "https://pr-42.preview.example.com"})
print(r.status_code, r.headers["access-control-allow-origin"],
r.headers["access-control-expose-headers"])
preflight("http://localhost:5173", "PUT", "authorization, content-type")
preflight("http://localhost:5173", "PATCH")
preflight("https://evil.example", "GET")
preflight("http://localhost:5173", "GET", "x-api-key")
Output:
200 https://pr-42.preview.example.com X-Total-Count
http://localhost:5173 PUT -> 200 OK
allow-origin: http://localhost:5173
http://localhost:5173 PATCH -> 400 Disallowed CORS method
allow-origin: http://localhost:5173
https://evil.example GET -> 400 Disallowed CORS origin
allow-origin: None
http://localhost:5173 GET -> 400 Disallowed CORS headers
allow-origin: http://localhost:5173
Unlike Flask, Starlette rejects a disallowed preflight with 400 and a short text explaining why, which is handy when debugging.
Details worth knowing:
- the defaults are restrictive:
allow_origins=[],allow_methods=["GET"],allow_credentials=False. If you add the middleware with no arguments, nothing cross-origin works. allow_origin_regexmust match the whole origin; it's useful for preview deployments with dynamic subdomains- the middleware wraps the whole app, so CORS headers are added even to error responses raised with
HTTPException. An unhandled exception that produces a500fromServerErrorMiddleware, however, comes back without CORS headers and shows up in the browser as a CORS error.
Django: django-cors-headers
For Django the standard choice is django-cors-headers (pip install django-cors-headers). Configure it in settings.py:
INSTALLED_APPS = [
# ...
"corsheaders",
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware", # as high as possible
"django.middleware.common.CommonMiddleware",
# ...
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:5173",
"https://app.example.com",
]
CORS_ALLOWED_ORIGIN_REGEXES = [r"^https://\w+\.preview\.example\.com$"]
CORS_URLS_REGEX = r"^/api/.*$"
CORS_ALLOW_CREDENTIALS = True
CorsMiddleware must come before any middleware that can generate a response, such as CommonMiddleware, otherwise those responses go out without CORS headers.
Credentials: cookies and Authorization
By default fetch doesn't send cookies on cross-origin requests. The front-end has to opt in:
fetch("https://api.example.com/api/me", { credentials: "include" })
and the server must respond with:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
The browser rejects a credentialed response that uses Access-Control-Allow-Origin: *. With credentials you must echo the exact origin. The same applies to * in Access-Control-Allow-Methods and Access-Control-Allow-Headers: with credentials, the wildcard is treated as a literal name, not "everything".
Also remember that cross-site cookies need SameSite=None; Secure, otherwise the browser won't send them no matter what the CORS headers say.
Sending a token in an Authorization header doesn't need Access-Control-Allow-Credentials (that flag is about cookies and HTTP auth managed by the browser), but Authorization must be listed in Access-Control-Allow-Headers because it triggers a preflight.
Avoiding CORS in development
During development you can often skip CORS entirely by making the front-end and API share an origin. Vite, webpack-dev-server and Next.js can proxy API calls:
// vite.config.js
export default {
server: {
proxy: { "/api": "http://localhost:5000" },
},
};
The browser talks only to http://localhost:5173, the dev server forwards /api/* to Flask, and no CORS headers are needed. In production a reverse proxy such as nginx can do the same by serving the static front-end and the API under one domain.
Common mistakes
- Fixing it on the client. Adding
Access-Control-Allow-Originto the request does nothing, andmode: "no-cors"gives you an opaque response you can't read. The server has to send the headers. allow_origins=["*"]with credentials. Browsers reject it. List the origins explicitly.- Trailing slash or wrong scheme. The
Originheader ishttps://app.example.com, neverhttps://app.example.com/. An allow-list entry with a trailing slash never matches. - Reflecting any
Originwith credentials. Echoing back whateverOriginarrives together withAccess-Control-Allow-Credentials: truelets any website make authenticated requests on behalf of your logged-in users. Always check against an allow-list. - Preflight blocked by auth. The browser never sends cookies or
Authorizationwith theOPTIONSpreflight. If your auth layer returns401forOPTIONS, every non-simple request fails. LetOPTIONSthrough (the extensions above do this for you). - Missing
Vary: Origin. When you echo a specific origin, a CDN may cache the response for one origin and serve it to another. - Thinking CORS protects the API. It only controls what browsers let pages read. Use authentication and CSRF protection for real security.