
How to Enable CORS in Django
How to Enable CORS in Django êŽë š
If you've ever tried to connect your frontend app to your Django backend and suddenly hit an error that looks something like "has been blocked by CORS policy", you're not alone. Itâs frustrating, especially when your code seems fine.
So whatâs going on?
This is where CORS (Cross-Origin Resource Sharing) comes in. It's a browser security feature that blocks web pages from making requests to a different domain than the one that served the web page.
Itâs there to protect users, but if itâs not configured correctly, it can stop your app from working the way you want.
Letâs fix that.
In this article, Iâll walk you through everything you need to know to enable CORS in Django without headaches.
What is CORS and Why Should You Care?
Before you start changing settings, itâs important to understand what CORS is.
Imagine you have a frontend built with React running on http://localhost:3000
and a Django API running on http://localhost:8000
.
When the frontend tries to talk to the backend, your browser sees that theyâre not the same origin (they have different ports), and it blocks the request.
Thatâs CORS doing its job. It assumes you might be trying to do something unsafe â like stealing cookies or user data â so it steps in.
Now, as a developer, if you trust the frontend and you own both ends, then itâs safe to let those requests through. You just need to tell Django itâs okay.
How to Enable CORS in Django
Youâre going to need a third-party package called django-cors-headers
. Itâs widely used and actively maintained. Hereâs how to set it up:
1. Install django-cors-headers
Run this in your terminal:
pip install django-cors-headers
This adds the package to your environment so Django can use it.
2. Add It to INSTALLED_APPS
Open your settings.py
file and find the INSTALLED_APPS
section. Add this line:
INSTALLED_APPS = [
...
'corsheaders',
]
This registers the app with Django.
3. Add Middleware
Now scroll down to the MIDDLEWARE
section in settings.py
. Add this at the top of the list:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
Why at the top? Because middleware in Django runs in order. If you donât place it at the top, the CORS headers might not be added correctly, and your browser will still block your requests.
4. Set the Allowed Origins
This is where you tell Django which origins are allowed to talk to your backend.
Still in settings.py
, add:
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]
Replace localhost:3000
with whatever domain or port your frontend is using. If you're using HTTPS or deploying, make sure to include the correct URL, like https://yourfrontend.com
.
And thatâs it! Youâre now allowing your frontend to access your backend.
Optional Settings You Might Need
Depending on your project, you might run into other issues. Here are some extra settings you might find useful:
Allow All Origins (Not Recommended for Production)
If youâre just testing and want to allow everything (be careful with this), you can use:
CORS_ALLOW_ALL_ORIGINS = True
Again, donât use this in production unless you understand the risks. It can open up your API to abuse.
Allow Credentials (Cookies, Auth)
If your frontend is sending authentication credentials like cookies or tokens, you also need this:
CORS_ALLOW_CREDENTIALS = True
And make sure you donât use CORS_ALLOW_ALL_ORIGINS
with this setting â it wonât work due to security rules. Stick to CORS_ALLOWED_ORIGINS
.
Allow Specific Headers
By default, common headers are allowed, but if youâre sending custom ones (like X-Auth-Token
), you can add:
CORS_ALLOW_HEADERS = [
"content-type",
"authorization",
"x-auth-token",
...
]
Example: Full Settings File Snippet
Hereâs a mini version of what your settings.py
might look like after setup:
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]
CORS_ALLOW_CREDENTIALS = True
You can tweak this based on your needs, but thatâs the basic structure.
Common Errors (And How to Fix Them)
1. CORS Not Working At All?
Double check:
- You added
corsheaders.middleware.CorsMiddleware
it at the top of the middleware list. - Your frontend origin matches exactly, including port and protocol.
- You restarted your server after changing the settings.
2. Preflight Request Fails (OPTIONS method)
Sometimes your browser sends an OPTIONS
request first to check if the server will allow the real request. Make sure your views or Django setup allow that method, or Django will return a 405 error.
You donât usually need to do anything here unless youâre using a custom middleware or view decorator that blocks it.
3. Using Django Rest Framework?
No problem â django-cors-headers
works out of the box. Just make sure itâs installed and the middleware is set up correctly.
FAQs
Can I allow multiple frontend URLs?
Yes! Just add more items to the list:
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"https://myfrontend.com",
]
Does CORS affect local development only?
No, it applies in production too. Any time your frontend and backend are on different origins (different domain or port), you need to handle CORS.
Is it secure to allow all origins?
No. Only do that temporarily during development. Always restrict access in production to just the domains you trust.
Do I need to change anything on the frontend?
Sometimes. If you're sending credentials (like cookies), youâll need to set credentials: "include"
in your fetch or Axios requests.
Example with fetch:
fetch("http://localhost:8000/api/data", {
method: "GET",
credentials: "include",
})
Final Thoughts
CORS can feel like a wall you keep running into when building web apps. But once you get the hang of how it works â and how to set it up in Django â it becomes a small thing you configure and move on.
Just remember:
- Be specific in production
- Always restart the server after changes
- Donât ignore warnings in your browser console â theyâre your friends
Now you know how to enable CORS in Django the right way.
Further Resources
