Fix CORS in Django
Last updated: April 2026
Browser Console Error
Access to fetch at 'http://localhost:8000/api/' from origin 'http://localhost:5173'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present.
Install django-cors-headers and add it to your Django settings. It handles preflight OPTIONS requests automatically.
Install and configure
pip install django-cors-headers
# settings.py
INSTALLED_APPS = [
...
"corsheaders",
...
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware", # must be first
"django.middleware.common.CommonMiddleware",
...
]
CORS_ALLOWED_ORIGINS = [
"https://yourapp.com",
"http://localhost:5173", # Vite
"http://localhost:3000", # CRA
]
With credentials (cookies or Authorization)
CORS_ALLOWED_ORIGINS = [
"https://yourapp.com",
"http://localhost:5173",
]
CORS_ALLOW_CREDENTIALS = True
โ Do not use
CORS_ALLOW_ALL_ORIGINS = True with CORS_ALLOW_CREDENTIALS = True. Use explicit origins.Wildcard (no credentials)
CORS_ALLOW_ALL_ORIGINS = True # safe without credentials
Regex origins for subdomains
CORS_ALLOWED_ORIGIN_REGEXES = [
r"^https://\w+\.yourapp\.com$",
]
Verify preflight
curl -X OPTIONS http://localhost:8000/api/ -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: POST" -v 2>&1 | grep -i "access-control"