I am sending requests to Django server from next.js but I am getting error :403 Forbidden (CSRF cookie not set.), even after sending the csrf token.
I am running both Django server and next.js locally.
Requesting to same api from postman/insomnia works perfectly fine but not with my next.js app.
I did some digging and found it may be issue with CORS, so I did some changes in settings.py but still getting same error.
Please help me understand what is going wrong, how I can debug, and what changes should I make.
First, I fetch CSRF token using another API which works fine.
Then in second api, I add my CSRF token.
fetching in Next.js
const uploadFile = async () => {
// Select file from input element or any other method
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const form = new FormData();
form.append("image", file);
const options = {
method: 'POST',
headers: {
cookie: 'csrftoken=2V7dKpZXLN24pLDdDkub9GxM2ljzI0nI',
'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001',
'X-CSRFToken': '2V7dKpZXLN24pLDdDkub9GxM2ljzI0nI'
}
};
options.body = form;
fetch('http://127.0.0.1:8000/getinfo', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
};
my settings.py in Django :
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'mymedic.pythonanywhere.com',
'127.0.0.1',
]
# Application definition
INSTALLED_APPS = [
'backend.apps.BackendConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CSRF_COOKIE_HTTPONLY=False
SESSION_COOKIE_SECURE=False
CSRF_COOKIE_SECURE=False
CORS_ALLOW_CREDENTIALS = True
# /questions/53215045/redirect-is-not-allowed-for-a-preflight-request
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'user',
'apikey',
'Referer',
'credentials',
'image,'
'username',
)
CORS_ALLOWED_ORIGINS = [
'http://localhost:3000', # Add the origin of your Next.js application
]
CORS_ALLOW_ALL_ORIGINS = False # Disable allowing all origins
CSRF_TRUSTED_ORIGINS = [
'http://localhost:3000',
'https://*.mydomain.com',
'https://*.127.0.0.1'
]
2