question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cookies are not set with fetchBaseQuery

See original GitHub issue

Hello,

I have tried setting cookies using RTK Query’s fetchBaseQuery with the option credentials: ‘include’, but it is not working. While doing the same request using fetch does work and sets the cookies like it should.

My server is running on: http://127.0.0.1:4000/api

I am using webpack, and I tried without any proxy and with these 2 proxies, but it won’t work in any case:

        proxy: {
            '/api':{
                changeOrigin: true,
                cookieDomainRewrite: 'localhost',
                target: 'http://localhost:4000',
                onProxyReq: (proxyReq) => {
                    if (proxyReq.getHeader('origin')) {
                      proxyReq.setHeader('origin', 'http://localhost:4000')
                    }
                }
            }
        }
     proxy: {
            '/api': {
               target: {
                  host: "127.0.0.1",
                  protocol: 'http:',
                  port: 4000
               },
               withCredentials: true,
            }
        },

This is authApi.tsx:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { LoginValues } from '../../schema/login.interfaces';

export const authApi = createApi({
  reducerPath: 'authApi',
  baseQuery: fetchBaseQuery({
    baseUrl: "http://127.0.0.1:8080/api", // "http://127.0.0.1:4000/api" when using no proxy in webpack
    credentials: 'include', //Tried here
  }),
  endpoints: (builder) => ({
    login: builder.mutation<void, LoginValues>({
      query: (user) => ({
        url: '/auth/login',
        method: 'POST',
        body: user,
        // credentials: 'include', //And here
      }),
    }),
  }),
});

export const { useLoginMutation } = authApi;

Here is how I use it

export const LoginContainer: React.FC = () => {

  const [login, result] = useLoginMutation();

   const submit = async (data: LoginFormValues) => {
    // This calls the api and returns the right cookies in Set-Cookie header, but cookies are not set in the Application
    await login({
        email: 'hi@c.com',
         password: 'hellohello',
     });


    // But when I try it with a simple fetch like the following, it returns the right cookies and they are set in the Application
    // Tried with no proxy on webpack
    // const rawResponse = await fetch('http://localhost:4000/api/auth/login', {
    //   method: 'POST',
    //   headers: {
    //     Accept: 'application/json',
    //     'Content-Type': 'application/json',
    //   },
    //   body: JSON.stringify({
    //     email: 'hi@c.com',
    //     password: 'hellohello',
    //   }),
    //   credentials: 'include',
    // });

  };
  return (
    <>
      <Button onClick={submit}>Login</Button>
    </>
  );


}
export default LoginContainer;

Any idea how to set those cookies ?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
CJ-0221commented, Oct 7, 2022

I had the same issue. Turned out that chrome was filtering out the cookies from the request because it was a “cross-site” request and the “secure”-flag on the Cookie was set to false.

So after setting sameSite: “None”, secure: true it’s now working.

I tried doing same but it’s ignoring. Could you pls share how you did it. Btw I’m using fetch. Pls suggest

1reaction
Hazem-Ben-Abdelhafidhcommented, Sep 14, 2022

so what’s the solution to this? I’m facing the same problem req.cookies always return that ugly [Object: null prototype] {} …

Read more comments on GitHub >

github_iconTop Results From Across the Web

Set-Cookie header from NestJS server not accepted by ...
I'm trying to do authorization using JWT access&refresh tokens (Next.js SSR + Redux Toolkit RTK Query + NestJS). When I receive a response ......
Read more >
fetchBaseQuery - Redux Toolkit
fetchBaseQuery. This is a very small wrapper around fetch that aims to simplify HTTP requests. It is not a full-blown replacement for axios ......
Read more >
React + Redux Toolkit: JWT Authentication and Authorization
This component will check if the user is logged in or authorized to access a particular page. The server will send three cookies...
Read more >
Fetching data in Redux using RTK Query - OpenReplay Blog
<ApiProvider /> : This can be used as a Provider if you do not already ... We will use the createApi and fetchBaseQuery...
Read more >
Fetch, CORS, and Cookies - YouTube
This tutorial explains the process of setting cookies in the browser as well as from the server. It shows the process of setting...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found