I am having a dumb moment. I use Tanstack Query and Ky in my app to make requests and inject jwt tokens in them. Every time a request hits a 403 error, the request gets resent after acquiring a new access token.
The annoying thing is when 403 occurs it shows a 403 error in the console originating from timeout.ts. And the stack goes through the whole request proccess from Ky to Tanstack Query and I don't know here to handle it so I can just post 'Getting new token' to console instead of this error.
I tried checking response.status in const request in useInfiniteLogsQuery, tried ky's beforeError hook and tinkered with the response in customKy but nothing seems to affect this error.
GET http://localhost:8080/api/v1/users/root/ 403 (Forbidden) timeout.ts:24
Here's the QueryClient:
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { PropsWithChildren, useState } from "react";
const QueryProvider = ({ children }: PropsWithChildren) => {
const [queryClientInstance] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 30,
retry: false,
},
},
})
);
return (
<QueryClientProvider client={queryClientInstance}>
{children}
</QueryClientProvider>
);
};
export default QueryProvider;
Here's the custom ky instance I use:
import useAuth from "hooks/useAuth";
import ky from "ky";
export const useKy = () => {
const { auth, setAuth, refreshToken } = useAuth();
const customKy = ky.extend({
prefixUrl: "api/v1",
hooks: {
beforeRequest: [
async (request) => {
if (auth)
request.headers.set("Authorization", `Bearer ${auth.access_token}`);
},
],
afterResponse: [
async (request, _, response) => {
if (response.status === 403) {
console.log(response);
try {
await refreshToken().then(({ access_token, username }) => {
setAuth({ access_token, username });
request.headers.set("Authorization", `Bearer ${access_token}`);
});
return ky(request);
} catch (error) {
throw new Error("Failed to refresh token: " + error);
}
}
},
],
},
retry: {
methods: ["get", "post"],
limit: 3,
statusCodes: [403],
},
});
return { customKy };
};
One of the queries:
export const useInfiniteLogsQuery = () => {
const { customKy } = useKy();
return useInfiniteQuery({
queryKey: ["infiniteLogs"],
queryFn: async ({ pageParam }) => {
const link = pageParam.split("api/v1/")[1];
const resolvedLink = `${link}&resolved=false`;
const request = await customKy.get<LogsResponse>(resolvedLink).json();
return request;
},
initialPageParam: `api/v1/logs-list/json/?limit=25&offset=0`,
getNextPageParam: (lastPage) => lastPage?.next,
});
};

timeout: falsetoky.extendand now the error doesn't showtimeout.tsbut showsKy.ts. I guess the error is from Ky but the question still stands.beforeErrorhook.