Django CORS Headers

4.9.0 · active · verified Sun Apr 05

django-cors-headers is a Django application that simplifies the handling of server headers required for Cross-Origin Resource Sharing (CORS). It provides a robust and flexible solution to manage cross-origin requests, allowing Django applications to securely interact with frontend applications hosted on different domains. The current version is 4.9.0, and it maintains an active release cadence with regular updates and community support.

Warnings

Install

Imports

Quickstart

To quickly enable CORS, install the package, then add `corsheaders` to your `INSTALLED_APPS` and `CorsMiddleware` to the top of your `MIDDLEWARE` list in `settings.py`. Finally, configure `CORS_ALLOWED_ORIGINS` with a list of allowed frontend domains. For development, `CORS_ALLOW_ALL_ORIGINS = True` can be used temporarily but is not recommended for production due to security risks. Remember that middleware order is crucial for correct functionality.

# settings.py

INSTALLED_APPS = [
    # ... other apps
    'corsheaders',
    # ...
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # ... other middleware
]

# Whitelist specific origins. In production, avoid CORS_ALLOW_ALL_ORIGINS = True.
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    # Add your frontend domains here, e.g., "https://yourfrontend.com"
]

# Optional: Allow credentials (cookies, auth headers) to be sent cross-origin
# CORS_ALLOW_CREDENTIALS = True

# Optional: If you need to allow all origins for development (use with caution in production!)
# CORS_ALLOW_ALL_ORIGINS = False # Set to True for development, but remove for production

# Example for allowing specific HTTP methods if you deviate from default allowed methods
# CORS_ALLOW_METHODS = [
#     'DELETE',
#     'GET',
#     'OPTIONS',
#     'PATCH',
#     'POST',
#     'PUT',
# ]

view raw JSON →