1

I have a server-side rendered Next.js/express app that communicates with a Django API (cross-origin). I login a user like so:

const response = await fetch('localhost:8000/sign-in', {
                method: 'POST',
                credentials: 'include',
                body: JSON.stringify({ email, password }),
                headers: { 'Content-Type': 'application/json' },
            });
const result = await response.json();
if (response.status === 200) {
    Router.push('/account');
}

Django successfully logs in the user and returns set-cookie headers for the csrftoken and sessionid cookies, however, when I navigate to a different page (like in the above code when I Router.push), the cookies don't persist.

I assume this has something to do with server-side vs. client-side, but when cookies are set in the browser I expect them to persist regardless.

How can I get these cookies, once set, to persist across all pages on the client side?

cph2117
  • 2,651
  • 1
  • 28
  • 41

1 Answers1

-1

It turns out that set-cookie is the old way of doing things. It's controlled by the browser, so it's obfuscated.

I ended up sending the csrftoken and sessionid back to the client in the JSON body, and saving them to localStorage using localStorage.setItem('sessionid', 'theSessionId') and localStorage.setItem('csrftoken', 'theCsrftoken').

Then when I need to make an authenticated request, I include them in the fetch headers:

const response = await fetch(`${API_HOST}/logout`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': localStorage.getItem('csrftoken'),
            sessionid: localStorage.getItem('sessionid'),
        },
    }); 
cph2117
  • 2,651
  • 1
  • 28
  • 41
  • storing cookies in `localStorage` is **NOT** safe! See [this](https://stackoverflow.com/questions/54258233/do-i-have-to-store-tokens-in-cookies-or-localstorage-or-session) – empflow Jul 06 '23 at 12:17