CORSConfigurationError
aiohttp.web_exceptions.HTTPForbidden: CORS policy error
Stack trace
aiohttp.web_exceptions.HTTPForbidden: CORS policy error: Origin 'http://localhost:3000' is not allowed by Access-Control-Allow-Origin.
Why it happens
CORS (Cross-Origin Resource Sharing) restricts web pages from making requests to a different domain than the one that served the web page. If the backend server does not explicitly allow the frontend's origin in its CORS policy, browsers block the request, causing this error. This often happens when the server's CORS middleware is missing, misconfigured, or the allowed origins list is incomplete.
Detection
Monitor browser console logs for CORS errors and backend server logs for HTTP 403 responses related to CORS headers. Use automated tests to verify CORS headers on API responses.
Causes & fixes
Backend server lacks CORS middleware or configuration
Add and configure CORS middleware (e.g., flask-cors, aiohttp_cors, or FastAPI's CORSMiddleware) to explicitly allow frontend origins.
Allowed origins list does not include the frontend domain or localhost during development
Update the CORS configuration to include all necessary frontend origins, including localhost and deployed domains.
CORS headers are set incorrectly or overridden by other middleware
Ensure CORS headers are set last in the middleware chain and not overwritten by other response handlers.
Frontend requests include credentials but server CORS policy does not allow credentials
Set 'Access-Control-Allow-Credentials' to true on the server and ensure allowed origins are not wildcard '*' when credentials are used.
Code: broken vs fixed
from fastapi import FastAPI
app = FastAPI()
@app.get('/api/data')
def get_data():
return {'message': 'Hello from AI backend'}
# This will cause CORS errors if frontend is on a different origin import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
'http://localhost:3000', # Add your frontend origin here
'https://your-production-frontend.com'
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
@app.get('/api/data')
def get_data():
return {'message': 'Hello from AI backend'}
# Added CORSMiddleware with allowed origins to fix CORS errors Workaround
Temporarily disable CORS enforcement in the browser using extensions or flags during development, but fix server CORS configuration before production deployment.
Prevention
Implement strict CORS policies on the backend with explicit allowed origins and credentials settings, and include CORS tests in your CI pipeline to catch misconfigurations early.