Search code examples
djangocookiescross-domain

Django: set-cookie causes cookies to be stored in the backend instead of the frontend


  • example.com is frontend (Next.js)
  • api.example.com is backend (Django)

For some reason, the cookie is stored on the backend domain.

This does not allow the front-end to access the stored cookies.

I have implemented an authentication API using the following, but as far as I can tell, there is no setting to change the domain where cookies are stored.

  • django-cors-headers
  • dj-rest-auth
  • djangorestframework-simplejwt
CORS_ALLOWED_ORIGINS = ['https://example.com']
CORS_ALLOW_CREDENTIALS = True

How can I store cookies on the front-end domain?


Solution

  • I thinks you are looking for SESSION_COOKIE_DOMAIN

    The domain to use for session cookies. Set this to a string such as "example.com" for cross-domain cookies, or use None for a standard domain cookie.

    To use cross-domain cookies with CSRF_USE_SESSIONS, you must include a leading dot (e.g. ".example.com") to accommodate the CSRF middleware’s referer checking.

    Be cautious when updating this setting on a production site. If you update this setting to enable cross-domain cookies on a site that previously used standard domain cookies, existing user cookies will be set to the old domain. This may result in them being unable to log in as long as these cookies persist.

    also response.set_cookie has a domain argument as well