Allow a React or Vue frontend on one domain to make API calls to your Django backend on a different domain
Configure fine-grained CORS rules specifying which origins, methods, and headers your API accepts
Restrict cross-origin access to specific URL paths on your Django app rather than applying rules site-wide
Enable cookies to be sent in cross-site requests for session-based authentication across domains
The CORS middleware must appear early in the MIDDLEWARE list or other layers may return responses before CORS headers are attached.
django-cors-headers is a small add-on for Django, a popular Python web framework. Its job is to add the correct HTTP headers to server responses so that web browsers allow JavaScript running on one website to make requests to your Django app hosted on a different domain. This browser restriction is called the Same-Origin Policy, and CORS (Cross-Origin Resource Sharing) is the official mechanism for relaxing it in a controlled way. In practice, you need this whenever your frontend and backend are on different domains. For example, if your React app is at app.example.com and your API is at api.example.com, the browser will block the requests by default. Adding this package and listing the allowed origins in your Django settings file fixes that. Setup involves two steps: adding the package to Django's list of installed apps and inserting a middleware class into the request-handling chain. The middleware needs to appear early in that chain so it can attach the CORS headers before any other layer might return a response first. The main configuration options let you specify which domains are allowed to make cross-site requests. You can provide an explicit list of origins, a list of regular expression patterns for cases where the list would be too long (such as many subdomains), or a single flag to allow all origins. The last option is convenient for local development but the README cautions that it is unsafe for production because it lets any website make requests to your API. The package also exposes finer-grained settings for controlling which HTTP methods and headers are permitted, whether cookies may be included in cross-site requests, how long browsers should cache the permissions response, and which URL paths on your site CORS rules apply to.
← adamchainz on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.