Overview
This page is the atomic definition. API server CORS configuration lives at fastapi and nextjs.
Definition
Cross-Origin Resource Sharing (CORS) is an HTTP header-based protocol that lets a server tell browsers which external origins are permitted to read its responses. The browser enforces this: when JavaScript on app.example.com fetches api.example.com, the browser attaches an Origin request header. The server responds with Access-Control-Allow-Origin. If the origins do not match and no wildcard is present, the browser blocks the JavaScript from reading the response body. CORS does not prevent the request from reaching the server; it prevents the browser from exposing the response to the calling script. For requests with custom headers or non-simple methods (PUT, DELETE, PATCH), the browser first sends a preflight OPTIONS request. The server must respond with the appropriate Access-Control-Allow-Methods and Access-Control-Allow-Headers or the actual request is blocked. Setting Access-Control-Allow-Origin: * disables protection and should not be used on authenticated endpoints. csp is a distinct mechanism that controls which resources a page may load, not which responses it may read.
When it applies
Configure CORS on every API that is consumed by browser JavaScript from a different origin. Internal same-origin APIs (Next.js API routes called by the same Next.js app) do not require CORS headers. Public read-only APIs may use wildcard origins; authenticated APIs should specify exact allowed origins.
Example
A FastAPI backend at api.myapp.com adds:
app.add_middleware(
CORSMiddleware,
allow_origins=["https://myapp.com"],
allow_methods=["GET", "POST"],
allow_headers=["Authorization"],
)Requests from myapp.com succeed; requests from evil.com are blocked by the browser.
Related concepts
- csp - controls resource loading policy; operates in parallel with CORS.
- fastapi - FastAPI’s
CORSMiddlewareis the standard way to configure CORS in Python APIs. - nextjs - Next.js API routes support CORS via response headers or a middleware wrapper.
- http-codes - preflight failures return 4xx status codes logged in DevTools.
Citing this term
See CORS (llmbestpractices.com/glossary/cors).