Authentication with tanstack-router

I am implementing access and refresh-token based authentication on a project and on the signup and login route, I make a check in the before-load function, if user exists, if it does then he is redirected to the last page he was on from the signup or login page (implementing typical auth behaviour). But doing so is giving an error and the page doesn't load, if I comment out the code for before-load then everything works.
Error Message:
Request failed with status code 401

Stack Trace:
AxiosError: Request failed with status code 401
    at settle (http://localhost:3001/node_modules/.vite/deps/axios.js?v=d569e361:1235:12)
    at XMLHttpRequest.onloadend (http://localhost:3001/node_modules/.vite/deps/axios.js?v=d569e361:1566:7)
    at Axios.request (http://localhost:3001/node_modules/.vite/deps/axios.js?v=d569e361:2124:41)
    at async getMe (http://localhost:3001/src/api/authApi.ts:12:17)
. before-load:
  beforeLoad: async ({ context, search }) => {
    const user = await context.queryClient.ensureQueryData(userQueryOptions());
    if (user) {
      throw redirect({ to: search.redirect });
    }
  },
.
import { queryOptions, useQuery } from '@tanstack/react-query';
import { authApi } from '@/api/authApi';

export const userQueryOptions = () =>
  queryOptions({
    queryKey: ['user'],
    queryFn: authApi.getMe,
    staleTime: Number.POSITIVE_INFINITY,
    retry: false,
  });

function useUser() {
  const { data: user } = useQuery(userQueryOptions());
  return { user };
}
export default useUser;
The complete code can be found at : https://github.com/AyushShende25/blog-client
GitHub
Contribute to AyushShende25/blog-client development by creating an account on GitHub.
GitHub - AyushShende25/blog-client
Was this page helpful?