Cookies not accessible in react, but shown chrome developer tools. Django RF backend
I am having trouble getting tokens from cookies in frontend, although I can see the cookies set in chrome developer tools with httpOnly set to False. I am doing local development with:
- React frontend (http://localhost:3000/)
- Django backend (http://127.0.0.1:8000/)
- Chrome for web browser, chrome developer for debugging.
In Django rest framework, I have
# views.py
@method_decorator(ensure_csrf_cookie, name="dispatch")
class SetCsrfTokenAPIView(APIView):
permission_classes = (permissions.AllowAny,)
def get(self, request, format=None):
response = Response({"success": "CSRF cookie set"})
response.set_cookie(
"my_cookie", "cookie_value", max_age=3600, secure=True, samesite="None"
)
return response
# settings.py
CORS_ALLOW_ALL_ORIGINS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = "None"
# CSRF_COOKIE_SAMESITE = "Lax"
CSRF_COOKIE_HTTPONLY = False
CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"]
SESSION_COOKIE_SAMESITE = None
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
# "*",
]
INSTALLED_APPS = [
...
"rest_framework",
"corsheaders",
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
...
]
Using react frontend, i make a fetch request with to the endpoint that hits SetCsrfTokenAPIView.
const data = await fetch(
`${process.env.REACT_APP_API_URL}/auth/csrf/`,
{
method: "GET",
credentials: "include", // This is equivalent to Axios's `withCredentials: true`
headers: {
"Content-Type": "application/json",
},
}
);
Call is successful and I can see the token values in chrome developer tools token in Applications header in Network
However, when i use js-cookie, react-cookie or document.cookie to get the cookie contents, it cannot find any cookie set from django. If i write a cookie entry by hand on chrome developer, then react can find the handwritten cookies only. The keys and values (value of Secure, httpOnly, etc) are the same as the ones set from django
How can I access cookies in react frontend? My goal is to extract the value and submit the value using the X-CSRFToken header.
What I did so far
I have scavenged relevant django forums and stackoverflow here. Lots of posts comment on making HttpOnly to False in the backend cookie setting and in the frontend setting credentials: "include", in the requests. I also tried both fetch and axios.