feat(auth): enhance error handling for token expiration and unauthorized access
This commit is contained in:
@@ -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 } },
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user