Published at

Enabling CORS in Django REST Framework

Enabling CORS in Django REST Framework

A simple guide to enable CORS in Django REST Framework, with step-by-step instructions and configuration examples.

Authors
  • avatar
    Name
    James Lau
    Twitter
  • Indie App Developer at Self-employed
Sharing is caring!
Table of Contents

Cross-Origin Resource Sharing (CORS) is a crucial security feature implemented by web browsers to restrict web pages from making requests to a different domain than the one which served the web page. When building APIs with Django REST Framework, you’ll often need to enable CORS to allow your frontend (e.g., a React or Vue.js application) running on a different domain (or port) to access your API.

Here’s how to enable CORS in your Django REST Framework project:

1. Install the django-cors-headers package:

First, install the django-cors-headers package using pip:

python -m pip install django-cors-headers

This package provides the necessary middleware and settings to handle CORS headers.

2. Add corsheaders to your INSTALLED_APPS:

Next, add 'corsheaders' to your INSTALLED_APPS in your settings.py file:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

This tells Django to recognize and load the corsheaders app.

3. Add the CorsMiddleware:

Add the CorsMiddleware to your MIDDLEWARE list in settings.py. It’s important to place it before CommonMiddleware:

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

The CorsMiddleware intercepts HTTP requests and adds the necessary CORS headers to the responses.

4. Configure CORS settings:

Now, configure the CORS settings in your settings.py file. You have two main options:

Option 1: Allow all origins (for development):

For development purposes, you can allow all origins by setting CORS_ORIGIN_ALLOW_ALL to True:

CORS_ORIGIN_ALLOW_ALL = True

Warning: Never use this setting in production. It’s a security risk.

Option 2: Specify allowed origins (for production):

In production, you should explicitly specify the allowed origins using the CORS_ALLOWED_ORIGINS setting. This is a list of URLs that are permitted to make cross-origin requests:

CORS_ORIGIN_ALLOW_ALL = False

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3030',
]

Replace 'http://localhost:3030' with the actual origin(s) of your frontend application(s).

With these steps, you have successfully enabled CORS in your Django REST Framework project. Your frontend applications running on different origins can now communicate with your API.

Sharing is caring!