Skip to main content

django-cors-headers

https://img.shields.io/github/actions/workflow/status/adamchainz/django-cors-headers/main.yml.svg?branch=main&style=for-the-badge https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge https://img.shields.io/pypi/v/django-cors-headers.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django application from other origins.


Improve your Django and Git skills with my books.


About CORS

Adding CORS headers allows your resources to be accessed on other domains. It’s important you understand the implications before adding the headers, since you could be unintentionally opening up your site’s private data to others.

Some good resources to read on the subject are:

Requirements

Python 3.9 to 3.14 supported.

Django 4.2 to 6.0 supported.

Setup

Install from pip:

python -m pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]

Make sure you add the trailing comma or you might get a ModuleNotFoundError (see this blog post).

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django’s CommonMiddleware or Whitenoise’s WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

About

django-cors-headers was created in January 2013 by Otto Yiu. It went unmaintained from August 2015 and was forked in January 2016 to the package django-cors-middleware by Laville Augustin at Zeste de Savoir. In September 2016, Adam Johnson, Ed Morley, and others gained maintenance responsibility for django-cors-headers (Issue 110) from Otto Yiu. Basically all of the changes in the forked django-cors-middleware were merged back, or re-implemented in a different way, so it should be possible to switch back. If there’s a feature that hasn’t been merged, please open an issue about it.

django-cors-headers has had 40+ contributors in its time; thanks to every one of them.

Configuration

Configure the middleware’s behaviour in your Django settings. You must set at least one of three following settings:

  • CORS_ALLOWED_ORIGINS

  • CORS_ALLOWED_ORIGIN_REGEXES

  • CORS_ALLOW_ALL_ORIGINS

CORS_ALLOWED_ORIGINS: Sequence[str]

A list of origins that are authorized to make cross-site HTTP requests. The origins in this setting will be allowed, and the requesting origin will be echoed back to the client in the access-control-allow-origin header. Defaults to [].

An Origin is defined by the CORS RFC Section 3.2 as a URI scheme + hostname + port, or one of the special values 'null' or 'file://'. Default ports (HTTPS = 443, HTTP = 80) are optional.

The special value null is sent by the browser in “privacy-sensitive contexts”, such as when the client is running from a file:// domain. The special value file:// is sent accidentally by some versions of Chrome on Android as per this bug.

Example:

CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000",
]

Previously this setting was called CORS_ORIGIN_WHITELIST, which still works as an alias, with the new name taking precedence.

CORS_ALLOWED_ORIGIN_REGEXES: Sequence[str | Pattern[str]]

A list of strings representing regexes that match Origins that are authorized to make cross-site HTTP requests. Defaults to []. Useful when CORS_ALLOWED_ORIGINS is impractical, such as when you have a large number of subdomains.

Example:

CORS_ALLOWED_ORIGIN_REGEXES = [
    r"^https://\w+\.example\.com$",
]

Previously this setting was called CORS_ORIGIN_REGEX_WHITELIST, which still works as an alias, with the new name taking precedence.

CORS_ALLOW_ALL_ORIGINS: bool

If True, all origins will be allowed. Other settings restricting allowed origins will be ignored. Defaults to False.

Setting this to True can be dangerous, as it allows any website to make cross-origin requests to yours. Generally you’ll want to restrict the list of allowed origins with CORS_ALLOWED_ORIGINS or CORS_ALLOWED_ORIGIN_REGEXES.

Previously this setting was called CORS_ORIGIN_ALLOW_ALL, which still works as an alias, with the new name taking precedence.


The following are optional settings, for which the defaults probably suffice.

CORS_URLS_REGEX: str | Pattern[str]

A regex which restricts the URL’s for which the CORS headers will be sent. Defaults to r'^.*$', i.e. match all URL’s. Useful when you only need CORS on a part of your site, e.g. an API at /api/.

Example:

CORS_URLS_REGEX = r"^/api/.*$"

CORS_ALLOW_METHODS: Sequence[str]

A list of HTTP verbs that are allowed for the actual request. Defaults to:

CORS_ALLOW_METHODS = (
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
)

The default can be imported as corsheaders.defaults.default_methods so you can just extend it with your custom methods. This allows you to keep up to date with any future changes. For example:

from corsheaders.defaults import default_methods

CORS_ALLOW_METHODS = (
    *default_methods,
    "POKE",
)

CORS_ALLOW_HEADERS: Sequence[str]

The list of non-standard HTTP headers that you permit in requests from the browser. Sets the Access-Control-Allow-Headers header in responses to preflight requests. Defaults to:

CORS_ALLOW_HEADERS = (
    "accept",
    "authorization",
    "content-type",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
)

The default can be imported as corsheaders.defaults.default_headers so you can extend it with your custom headers. This allows you to keep up to date with any future changes. For example:

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = (
    *default_headers,
    "my-custom-header",
)

CORS_EXPOSE_HEADERS: Sequence[str]

The list of extra HTTP headers to expose to the browser, in addition to the default safelisted headers. If non-empty, these are declared in the access-control-expose-headers header. Defaults to [].

CORS_PREFLIGHT_MAX_AGE: int

The number of seconds the browser can cache the preflight response. This sets the access-control-max-age header in preflight responses. If this is 0 (or any falsey value), no max age header will be sent. Defaults to 86400 (one day).

Note: Browsers send preflight requests before certain “non-simple” requests, to check they will be allowed. Read more about it in the CORS MDN article.

CORS_ALLOW_CREDENTIALS: bool

If True, cookies will be allowed to be included in cross-site HTTP requests. This sets the Access-Control-Allow-Credentials header in preflight and normal responses. Defaults to False.

Note: in Django 2.1 the SESSION_COOKIE_SAMESITE setting was added, set to 'Lax' by default, which will prevent Django’s session cookie being sent cross-domain. Change the setting to 'None' if you need to bypass this security restriction.

CORS_ALLOW_PRIVATE_NETWORK: bool

If True, allow requests from sites on “public” IP to this server on a “private” IP. In such cases, browsers send an extra CORS header access-control-request-private-network, for which OPTIONS responses must contain access-control-allow-private-network: true.

Refer to:

CSRF Integration

Most sites will need to take advantage of the Cross-Site Request Forgery protection that Django offers. CORS and CSRF are separate, and Django has no way of using your CORS configuration to exempt sites from the Referer checking that it does on secure requests. The way to do that is with its CSRF_TRUSTED_ORIGINS setting. For example:

CORS_ALLOWED_ORIGINS = [
    "https://read-only.example.com",
    "https://read-and-write.example.com",
]

CSRF_TRUSTED_ORIGINS = [
    "https://read-and-write.example.com",
]

Signals

If you have a use case that requires more than just the above configuration, you can attach code to check if a given request should be allowed. For example, this can be used to read the list of origins you allow from a model. Attach any number of handlers to the check_request_enabled Django signal, which provides the request argument (use **kwargs in your handler to protect against any future arguments being added). If any handler attached to the signal returns a truthy value, the request will be allowed.

For example you might define a handler like this:

# myapp/handlers.py
from corsheaders.signals import check_request_enabled

from myapp.models import MySite


def cors_allow_mysites(sender, request, **kwargs):
    return MySite.objects.filter(host=request.headers["origin"]).exists()


check_request_enabled.connect(cors_allow_mysites)

Then connect it at app ready time using a Django AppConfig:

# myapp/__init__.py

default_app_config = "myapp.apps.MyAppConfig"
# myapp/apps.py

from django.apps import AppConfig


class MyAppConfig(AppConfig):
    name = "myapp"

    def ready(self):
        # Makes sure all signal handlers are connected
        from myapp import handlers  # noqa

A common use case for the signal is to allow all origins to access a subset of URL’s, whilst allowing a normal set of origins to access all URL’s. This isn’t possible using just the normal configuration, but it can be achieved with a signal handler.

First set CORS_ALLOWED_ORIGINS to the list of trusted origins that are allowed to access every URL, and then add a handler to check_request_enabled to allow CORS regardless of the origin for the unrestricted URL’s. For example:

# myapp/handlers.py
from corsheaders.signals import check_request_enabled


def cors_allow_api_to_everyone(sender, request, **kwargs):
    return request.path.startswith("/api/")


check_request_enabled.connect(cors_allow_api_to_everyone)

Metadata

Release files for django-cors-headers 4.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-cors-headers 4.9.0
File Size Uploaded
django_cors_headers-4.9.0.tar.gz 21.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-cors-headers 4.9.0
File Interpreter ABI Platform
django_cors_headers-4.9.0-py3-none-any.whl Python 3 none any Details

Total release size: 34.3 kB

Release files / django_cors_headers-4.9.0.tar.gz

Download URL django_cors_headers-4.9.0.tar.gz
Size 21.5 kB
Tags Source
SHA-256 checksum
How to use checksums
fe5d7cb59fdc2c8c646ce84b727ac2bca8912a247e6e68e1fb507372178e59e8
BLAKE2b-256 checksum
How to use checksums
213955822b15b7ec87410f34cd16ce04065ff390e50f9e29f31d6d116fc80456
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 18, 2025.

Transparency log

Release files / django_cors_headers-4.9.0-py3-none-any.whl

Download URL django_cors_headers-4.9.0-py3-none-any.whl
Size 12.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
15c7f20727f90044dcee2216a9fd7303741a864865f0c3657e28b7056f61b449
BLAKE2b-256 checksum
How to use checksums
30d819ed1e47badf477d17fb177c1c19b5a21da0fd2d9f093f23be3fb86c5fab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 18, 2025.

Transparency log

Release history Release notifications | RSS feed

This release

4.9.0 This release

2 release files

4.8.0

2 release files

4.7.0

2 release files

4.6.0

2 release files

4.5.0

2 release files

4.4.0

2 release files

4.3.1

2 release files

4.3.0

2 release files

4.2.0

2 release files

4.1.0

2 release files

4.0.0

2 release files

3.14.0

2 release files

3.12.0

2 release files

3.11.0

2 release files

3.9.0

2 release files

3.8.0

2 release files

3.7.0

2 release files

3.6.0

2 release files

3.5.0

2 release files

3.4.0

2 release files

3.3.0

2 release files

3.2.1

2 release files

3.2.0

2 release files

3.1.1

2 release files

3.1.0

2 release files

3.0.2

2 release files

3.0.1

2 release files

3.0.0

2 release files

2.5.3

2 release files

2.5.2

2 release files

2.5.1

2 release files

2.5.0

2 release files

2.4.1

2 release files

2.4.0

2 release files

2.3.0

2 release files

2.2.1

2 release files

2.2.0

2 release files

2.1.0

2 release files

2.0.2

2 release files

2.0.1

2 release files

2.0.0

2 release files

1.3.1

2 release files

1.3.0

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.0

1 release file

1.0.0

1 release file

0.13

1 release file

0.12

1 release file

0.11

1 release file

0.10

1 release file

0.06

1 release file

0.05

1 release file

0.04

1 release file

0.03

1 release file

0.02

1 release file

0.01

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page