{"id":8148,"library":"fastapi-cors","title":"FastAPI CORS (Env Config)","description":"A lightweight Python library (version 0.0.6) that provides a simplified, environment variable-driven configuration for CORS settings in FastAPI applications. It acts as a wrapper around FastAPI's native `CORSMiddleware` (from Starlette), allowing developers to manage CORS policies such as allowed origins, methods, headers, and credentials through environment variables rather than direct code configuration.","status":"active","version":"0.0.6","language":"en","source_language":"en","source_url":"https://github.com/leosussan/fastapi-cors","tags":["fastapi","cors","middleware","environment-variables","http"],"install":[{"cmd":"pip install fastapi-cors","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Required for core application functionality, fastapi-cors is a wrapper for its middleware.","package":"fastapi"},{"reason":"Commonly used to load environment variables for configuration.","package":"python-dotenv","optional":true}],"imports":[{"symbol":"FastAPI","correct":"from fastapi import FastAPI"},{"note":"This library (fastapi-cors) provides its own wrapper `CORS` class, distinct from FastAPI's native `CORSMiddleware`.","wrong":"from fastapi.middleware.cors import CORSMiddleware","symbol":"CORS","correct":"from fastapi_cors import CORS"}],"quickstart":{"code":"import os\nfrom fastapi import FastAPI\nfrom fastapi_cors import CORS\n\n# Example of setting environment variables (usually done in a .env file or deployment config)\n# For local testing, you can uncomment these or use python-dotenv\nos.environ['CORS_ALLOW_ORIGINS'] = 'http://localhost:3000,https://example.com'\nos.environ['CORS_ALLOW_METHODS'] = 'GET,POST'\nos.environ['CORS_ALLOW_CREDENTIALS'] = 'true'\n\napp = FastAPI()\n\n# Initialize fastapi-cors. It reads settings from environment variables automatically.\n# You can pass include_health_check=False if not needed.\nCORS(app)\n\n@app.get(\"/\")\ndef read_root():\n    return {\"Hello\": \"World\"}\n\n@app.post(\"/items/\")\ndef create_item(item: dict):\n    return {\"item\": item, \"message\": \"Item created\"}\n\n# To run this app: uvicorn your_module_name:app --reload\n# Make sure to set the environment variables before running.","lang":"python","description":"This quickstart demonstrates how to integrate `fastapi-cors` into a FastAPI application. The library automatically configures CORS based on environment variables like `CORS_ALLOW_ORIGINS`, `CORS_ALLOW_METHODS`, and `CORS_ALLOW_CREDENTIALS`. You simply instantiate the `CORS` class with your FastAPI app, and it applies the middleware based on the current environment settings."},"warnings":[{"fix":"Use `from fastapi_cors import CORS` and configure via environment variables (e.g., `CORS_ALLOW_ORIGINS`). If you prefer direct code configuration, use `from fastapi.middleware.cors import CORSMiddleware` instead.","message":"Do not confuse `fastapi-cors.CORS` with `fastapi.middleware.cors.CORSMiddleware`. While `fastapi-cors` uses the latter internally, its API is different and relies on environment variables for configuration.","severity":"gotcha","affected_versions":"All versions of fastapi-cors (0.0.x)"},{"fix":"When `CORS_ALLOW_CREDENTIALS` is 'true', `CORS_ALLOW_ORIGINS` must list specific origins, not `*` (e.g., `CORS_ALLOW_ORIGINS='http://localhost:3000,https://app.example.com'`).","message":"Using `allow_credentials=True` (set via `CORS_ALLOW_CREDENTIALS='true'`) with `allow_origins=['*']` (set via `CORS_ALLOW_ORIGINS='*'`) is a security violation according to the CORS specification and will be rejected by browsers.","severity":"breaking","affected_versions":"All versions"},{"fix":"Ensure `CORS(app)` is called immediately after `app = FastAPI()` creation, before `app.include_router()` or other `app.add_middleware()` calls.","message":"CORS middleware order is critical. The `CORS` instance (which adds the `CORSMiddleware`) must be added early in your FastAPI application's lifecycle, typically before any custom middleware or routers. Otherwise, some requests (especially those triggering exceptions) might bypass CORS headers.","severity":"gotcha","affected_versions":"All FastAPI versions"},{"fix":"After making CORS changes, clear your browser's cache, use an incognito/private browsing window, or use a tool like `curl` or Postman to test the API directly.","message":"Browser caching can cause persistent CORS errors even after fixing your backend configuration. The browser might have cached a preflight response indicating no access.","severity":"gotcha","affected_versions":"All versions (browser-side issue)"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure the `CORS_ALLOW_ORIGINS` environment variable (or equivalent if `fastapi-cors` isn't used) correctly includes the exact origin of your frontend (e.g., `CORS_ALLOW_ORIGINS='http://localhost:3000'` ). Remember to restart your FastAPI application after changing environment variables.","cause":"The backend FastAPI application is not configured to allow requests from the origin 'http://localhost:3000' (or the specified frontend origin). This is the most common CORS error.","error":"Access to fetch at 'http://localhost:8000/...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."},{"fix":"If `CORS_ALLOW_CREDENTIALS` is set to 'true', then `CORS_ALLOW_ORIGINS` must be a comma-separated list of specific origins (e.g., `'http://localhost:3000,https://app.yourdomain.com'`). Do not use `'*'`.","cause":"You are attempting to allow credentials (cookies, HTTP auth headers) from a frontend while simultaneously allowing requests from any origin (`*`), which is a security risk and forbidden by the CORS specification.","error":"The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'."},{"fix":"Check that `CORS_ALLOW_METHODS` includes the method being used (e.g., `POST`, `PUT`) and `CORS_ALLOW_HEADERS` includes any custom headers being sent. Also, ensure the FastAPI app is running and accessible.","cause":"This often indicates a failed CORS 'preflight' request (an `OPTIONS` HTTP method request sent by the browser before the actual request). This can be due to disallowed methods, headers, or a general network/server issue.","error":"Failed to load resource: net::ERR_FAILED (or similar network error on OPTIONS request)"}]}