Yoofi Brown-Pobee
Yoofi Brown-Pobee

Reputation: 393

React Remix not sending cookies to remote server

I am trying to set up authentication with Remix as my pure frontend and a django backend.

When the user signs in successfully, the backend sends a cookie with the response and this is set in the browser redirect with remix

const signIn = async (credentials: LoginCreds) => {
    try {
        const response = await fetch(generateFullBackendUrl('/auth/signin'), {
            method: 'POST',
            body: JSON.stringify(credentials),
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'include'
        });

        return response;
    } catch (e) {
        console.log(e);
    }
}

 const response = await authService.signIn({
        email,
        password
    })

    const cookies = response?.headers.get('set-cookie');

    if(cookies){
        return redirect('profile', {
            headers: {
                'Set-Cookie': cookies
            }
        });

However when I try to make subsequent fetch calls in my loader the cookies are not sent to the backend as I would expect the browser would

await fetch(generateFullBackendUrl('api/users/me'), {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            credentials: 'include'
        })

Front end is running on port 3000 Backend running on port 4000

Im wondering why the fetch request in the loader does not send the cookies with the request

Upvotes: 3

Views: 1963

Answers (2)

Suben Saha
Suben Saha

Reputation: 1848

There is a quick workaround but not so elegant solution:

in your loader use this:

export const loader: LoaderFunction = async({request}) => {
    const response = await fetch(`/api/books?${new URLSearchParams({
       limit: '10',
       page: '1',
       })}`, {
       headers: {
          'Cookie': request.headers.get('Cookie') || ''
       }
    });
    console.log(response)
    if(response.ok) return await response.json();
}

Upvotes: 2

Sergio Xalambrí
Sergio Xalambrí

Reputation: 1202

You need to read the cookie header from the loader request and pass it to your fetch headers.

There’s no way Fetch can automatically know what headers to send when used server side.

Upvotes: 2

Related Questions