Hello everyone,
I’m having a problem accessing the CSRF cookie in my Django project. My frontend is separate from my backend, and both use HTTPS. I’m trying to retrieve the csrftoken cookie in the frontend using a get_cookie(name) function, but I can’t get its value.
Here’s the code I use to retrieve the cookie:
const get_cookie = (name) => {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
};
const csrfToken = get_cookie('csrftoken');
However, document.cookie doesn’t return anything, even though I can see the csrftoken cookie in the “Cookies” tab of the browser’s development tools. I did check the cookie configuration in Django (CSRF_COOKIE_HTTPONLY = False), but this doesn’t seem to solve the problem.
Here’s Django’s configuration in settings.py :
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ["https://example.com"]
CSRF_TRUSTED_ORIGINS = ["https://example.com"]
CSRF_COOKIE_HTTPONLY = False
CSRF_USE_SESSIONS = False
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SAMESITE = 'None'
Details:
- The frontend and backend are on different domains.
- The backend is hosted on Railway, and I use HTTPS for both the frontend (https://example.com) and the backend.
- In my CORS configuration, I’ve added my frontend URL to CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS
I’ve also added credentials: ‘include’ to my fetch requests to make sure the cookies are sent, but I still can’t get the cookie value in JavaScript. The cookies are indeed present in the cookies tab in applications, but it’s impossible to retrieve them with “document.cookie”. I should also point out that these cookies are sent in the request header in the Cookies section.
Has anyone encountered a similar problem or can help me understand why I can’t access the cookie? I’m a bit lost and would really appreciate any help or suggestions.
Thanks in advance!