Skip to content

Authentication flow is not working normally with Redux Toolkit and RTK Query #4768

Description

@bylly1

Which project does this relate to?

Router

Describe the bug

I'm using TanStack Router with Redux Toolkit and RTK Query, but I noticed that the authentication flow is not working as expected. When I try to log in for the first time, even if the username and password are correct, the redirection doesn't work. However, if I try again with the correct credentials, it works. The same issue happens on logout.

After a lot of testing, I noticed that if I use a regular reducer: {} inside createSlice to set the isAuth flag to true, the redirection works normally. But if I use extraReducers: {}, it doesn't work.

Example:

# using reducer to set the isAuth flag the flow works normally

const authSliceBase = createSlice({
  name: 'auth',
  initialState: {
     isAuth: false
  },
  reducers: {
     setAuth: (status, { payload } => {
         state.isAuth = payload
     }
  }
});

# using extraReducers will not working as expected

const authSliceBase = createSlice({
  name: 'auth',
  initialState: {
     isAuth: false
  },
  reducers: {},
   builder.addMatcher(
      authApi.endpoints.login.matchFulfilled,
      (state, { payload }) => {
        state.isAuth = true;
      }
    ),
      builder.addMatcher(
        authApi.endpoints.logout.matchFulfilled,
        () => initialState
      );
});

Your Example Website or App

https://stackblitz.com/edit/vitejs-vite-kumuejx2

Steps to Reproduce the Bug or Issue

Open the repro link.
Try to login using credentials given in the example
After first try to login is not redirecting to protected route
After try second time will work but should redirect first time not second time

Expected behavior

Authentication flow should work like normal flow login redirect to protected and logout redirect to login page automatically

Screenshots or Videos

No response

Platform

  • Router / Start Version: ^1.129.4
  • OS: Windows
  • Browser: Chrome
  • Browser Version: 138
  • Bundler: vite
  • Bundler Version: 7.0.4

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions