Django CORS Configuration For Flutter Web

So, I was setting up a new Flutter web project which connects with Django API server and came across this error:

XMLHttpRequest error in flutter web

Turned out, I was missing some Cross Origin Resource Sharing (CORS) configuration for the backend.

Django CORS Configuration

Adding CORS support can simply by making use of django-cors-headers package which allows in-browser requests to your Django application from other origins.

Once you have installed the package, you need to add it to the INSTALLED_APPS.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # third party apps
    'corsheaders',

    # project apps

]

Next add the necessary middlewares:

MIDDLEWARE = [
    # cors should be placed before CsrfViewMiddleware
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    
    'django.middleware.csrf.CsrfViewMiddleware',
]

For the development environment, I have allowed all hosts and origins.

ALLOWED_HOSTS = ['*']
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True

These values should be configured properly for Production environments.

Finally, configure the headers:

CORS_ALLOW_HEADERS = (
    'content-disposition', 
    'accept-encoding', 
    'content-type', 
    'accept', 
    'origin', 
    'authorization',
    'cache-control'
)

That’s it.

flutter run -d chrome

No more CORS issue for Flutter web and Django server.

More Tutorials on Django