Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix: logout during 401

Carl-Gerhard Lindesvärd9db72d9e949b
diff --git a/apps/start/src/integrations/tanstack-query/root-provider.tsx b/apps/start/src/integrations/tanstack-query/root-provider.tsx
index 81ca44ff7..931ca33b6 100644
--- a/apps/start/src/integrations/tanstack-query/root-provider.tsx
+++ b/apps/start/src/integrations/tanstack-query/root-provider.tsx
@@ -1,5 +1,5 @@
import type { AppRouter } from '@openpanel/trpc';
-import { QueryClient } from '@tanstack/react-query';
+import { MutationCache, QueryCache, QueryClient } from '@tanstack/react-query';
import { createIsomorphicFn } from '@tanstack/react-start';
import { getRequestHeaders } from '@tanstack/react-start/server';
import { createTRPCClient, httpLink, TRPCClientError } from '@trpc/client';
@@ -20,6 +20,16 @@ function shouldRetryQuery(failureCount: number, error: unknown) {
return failureCount < DEFAULT_RETRY_COUNT;
}
+function handleUnauthorized(error: unknown) {
+ if (typeof window === 'undefined') return;
+ if (!(error instanceof TRPCClientError)) return;
+ if (error.data?.httpStatus !== 401) return;
+ if (window.location.pathname.startsWith('/login')) return;
+ // Hard navigation tears down in-flight refetches and WS subscriptions so
+ // the stale tab stops hammering the API after the session is gone.
+ window.location.assign('/login');
+}
+
export const getIsomorphicHeaders = createIsomorphicFn()
.server(() => {
const headers = getRequestHeaders();
@@ -97,6 +107,8 @@ export function getContext(apiUrl: string) {
dehydrate: { serializeData: superjson.serialize },
hydrate: { deserializeData: superjson.deserialize },
},
+ queryCache: new QueryCache({ onError: handleUnauthorized }),
+ mutationCache: new MutationCache({ onError: handleUnauthorized }),
});
// Create a tRPC client with cookies if provided