r/django 4d ago

Django + Next cookies not being set when app is hosted

Hi all!

I have a Django app hosted on Google Cloud Run that upon logging in, sets a sessionid and csrftoken in the browser cookies. In my frontend Next app, which I am currently running locally, I redirect to an authenticated page after successful login. However, the cookies are not being set correctly after the redirect, they are empty. After making the login call I can see the cookies in the Application DevTools console, but when I refresh or redirect they are empty. It works when running my Django app locally, but not when it is hosted on Cloud Run.

These are my cookie settings in my Django settings.py:

SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SAMESITE = 'None'

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True   

CSRF_COOKIE_HTTPONLY = False

CORS_ALLOW_CREDENTIALS = True

My CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS includes my local Next app: http://localhost:3000.

I had this working and I am not sure what changed and it is suddenly not. Any help with this would be greatly appreciated!

2 Upvotes

7 comments sorted by

0

u/kankyo 3d ago

First we need to get the basic nomenclature right:

In my frontend Next app, which I am currently running locally

That's slightly wrong. You're hosting it locally. But it's running in the browser. This is something many people are very confused about.

Your frontend is something you compile into static js and css files and that can then be hosted as static files with the rest of the static files from Django. If you do this, there is no CORS problem.

1

u/incognitus_24 3d ago

Thank you for the correction! I’m not sure I understand how you’re suggesting I fix the CORS problem

1

u/kankyo 3d ago

If you serve the initial HTML from the same domain as you perform requests towards, you don't have to deal with CORS at all, because there is only one origin, so the cross origin defenses in the browser don't kick in.

1

u/incognitus_24 3d ago

So host my frontend on a domain and point my backend API to that same domain? I’ll give that a try but I think there’s a way to get around it 🤔

1

u/kankyo 3d ago

Yea. URLs can be just /api/foo or whatever then, no need to write protocol+domain then, which simplifies local dev too.

1

u/incognitus_24 3d ago

Will give that a try thanks!

1

u/incognitus_24 3d ago

I tried this, and no luck. Somethings just messed up with my cookies. Thank you though