INSTALLED_APPS += ['corsheaders']
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # Must be before CommonMiddleware
'django.middleware.common.CommonMiddleware',
# ... other middleware
]
# Production CORS settings
CORS_ALLOWED_ORIGINS = [
'https://example.com',
'https://app.example.com',
]
# Allow credentials (cookies, authorization headers)
CORS_ALLOW_CREDENTIALS = True
# Allowed methods
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
# Custom headers
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
# Preflight cache (in seconds)
CORS_PREFLIGHT_MAX_AGE = 86400
Cross-Origin Resource Sharing (CORS) enables frontend apps on different domains to access your API. I use django-cors-headers for production-ready CORS handling. I configure CORS_ALLOWED_ORIGINS for specific domains in production and use CORS_ALLOW_ALL_ORIGINS only in development. For credentialed requests (cookies, auth headers), I set CORS_ALLOW_CREDENTIALS=True. I whitelist specific HTTP methods and headers as needed. Preflight caching with CORS_PREFLIGHT_MAX_AGE reduces overhead. This is essential for SPAs and mobile apps consuming Django APIs.