feat(auth): enhance error handling for token expiration and unauthorized access

This commit is contained in:
2026-03-14 03:00:30 +01:00
parent 791741fde0
commit c189056003
4 changed files with 41 additions and 23 deletions

View File

@@ -14,19 +14,30 @@ import { Toaster } from "@/components/ui/sonner";
import { ApiRequestError } from "@/lib/api";
function QueryProvider({ children }: { children: React.ReactNode }) {
const { setToken } = useAuthContext();
const { token, setToken } = useAuthContext();
const router = useRouter();
const [queryClient] = useState(() => {
const on401 = (error: unknown) => {
if (error instanceof ApiRequestError && error.status === 401) {
setToken(null);
router.push("/login");
}
};
return new QueryClient({
queryCache: new QueryCache({ onError: on401 }),
mutationCache: new MutationCache({ onError: on401 }),
queryCache: new QueryCache({
onError: (error) => {
// Only redirect on 401 if the user had a token (expired session).
// Guests hitting 401 on restricted content should not be redirected.
if (error instanceof ApiRequestError && error.status === 401 && token) {
setToken(null);
router.push("/login");
}
},
}),
mutationCache: new MutationCache({
onError: (error) => {
// Mutations always require auth — redirect on 401 regardless.
if (error instanceof ApiRequestError && error.status === 401) {
setToken(null);
router.push("/login");
}
},
}),
defaultOptions: { queries: { staleTime: 60 * 1000 } },
});
});