[Django]-Django ALLOWED_HOSTS vs CORS(django-cors-headers)

29👍

Doc on ALLOWED_HOSTS.
In short, in production environment where you have DEBUG=FALSE, your Django application will not serve in a domain or subdomain that is not specified in ALLOWED_HOSTS. It’s a whitelist of trusted domains you can serve your backend app on. In other words, these are the domains your backend app can be accessed from.

CORS on the other hand stands for Cross-Origin Resource Sharing. I’m assuming you are asking because you are also doing Django Rest Framework. CORS has nothing to do with which domain you serve your backend app on. Instead, it basically allows your frontend apps, like the multiple reactjs apps you mentioned, to interact with your APIs without having to deploy all of them on the same domain. django-cors-header is the recommended package for configuring CORS.

1👍

In short

  • ALLOWED_HOSTS lets you specify the host/domain the backend/server can run on
  • CORS lets you define which frontend/client origins are allowed to call your backend (apart from ones on the same scheme, domain, and port)
Note that:
  • ALLOWED_HOSTS is useful to prevent HTTP Host header attacks
  • It is important to note that CORS is only relevant for browsers. Furthermore, these settings are only needed because of the same-origin policy. Other servers, scripts, and programs will still be able to call your API regardless.
  • The main benefits of enabling CORS are for enabling restricted public APIs and allowing the browser to make cross-origin "credentialed" requests

Leave a comment