Django session cookies not persisting
I have a Django API which upon successful login, uses the Set-Cookie Response Headers to set a sessionId and CSRF Token in the cookies. I had it working and all of a sudden it stopped, the cookies no longer persist. After login I see them in the console, then when I refresh, they disappear. I am running my Next.js App locally with the Django API hosted on Google Cloud Run with a custom domain. Does anyone know what is going on?
Since your Django API is hosted on Google Cloud Run (likely using HTTPS), ensure your cookies are set correctly check Secure flag: Cloud Run enforces HTTPS, so your cookies must be marked as Secure. Check SameSite
attribute: By default, modern browsers block third-party cookies unless SameSite=None
; Secure is explicitly set.
check in settings.py file:
SESSION_COOKIE_SECURE = True # required for HTTPS
SESSION_COOKIE_SAMESITE = "None" # required for cross-origin requests
SESSION_COOKIE_HTTPONLY = True # helps prevent XSS attacks
CSRF_COOKIE_SECURE = True # required for HTTPS
CSRF_COOKIE_SAMESITE = "None" # required for cross-origin requests
CSRF_COOKIE_HTTPONLY = False # CSRF token needs to be accessible by JS for Next.js
when you are making API calls from Next.js, ensure you include credentials
fetch("https://your-api.com/login/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "include", // it ensures cookies are sent and received
body: JSON.stringify({ username, password }),
});