fix refresh issue

This commit is contained in:
yohlo
2025-09-24 12:20:36 -05:00
parent 36f3bb77d4
commit 81329e4354
7 changed files with 74 additions and 87 deletions

View File

@@ -4,6 +4,31 @@ import Passwordless from "supertokens-web-js/recipe/passwordless";
import { appInfo } from "./config";
import { logger } from "./";
let refreshAttemptCount = 0;
export const resetRefreshFlag = () => {
refreshAttemptCount = 0;
};
const setupFetchInterceptor = () => {
if (typeof window === 'undefined') return;
const originalFetch = window.fetch;
window.fetch = async (resource: RequestInfo | URL, options?: RequestInit) => {
const url = typeof resource === 'string' ? resource :
resource instanceof URL ? resource.toString() : resource.url;
if (url.includes('/api/auth/session/refresh')) {
refreshAttemptCount++;
if (refreshAttemptCount > 1) {
throw new Error('Duplicate refresh attempt blocked');
}
}
return originalFetch.call(window, resource, options);
};
};
export const frontendConfig = () => {
return {
appInfo,
@@ -12,7 +37,6 @@ export const frontendConfig = () => {
Session.init({
tokenTransferMethod: "cookie",
sessionTokenBackendDomain: undefined,
preAPIHook: async (context) => {
context.requestInit.credentials = "include";
return context;
@@ -23,16 +47,14 @@ export const frontendConfig = () => {
};
let initialized = false;
export function ensureSuperTokensFrontend() {
if (typeof window === "undefined") return;
if (!initialized) {
setupFetchInterceptor();
SuperTokens.init(frontendConfig());
initialized = true;
logger.info("Initialized");
Session.doesSessionExist().then((exists) => {
logger.info(`Session does${exists ? "" : "NOT"} exist on load!`);
});
logger.info("SuperTokens initialized");
}
}

View File

@@ -2,6 +2,8 @@ import { useMutation, UseMutationOptions } from "@tanstack/react-query";
import { ServerResult } from "../types";
import toast from '@/lib/sonner'
let isMutationRefreshingSession = false;
export function useServerMutation<TData, TVariables = unknown>(
options: Omit<UseMutationOptions<TData, Error, TVariables>, 'mutationFn'> & {
mutationFn: (variables: TVariables) => Promise<ServerResult<TData>>;
@@ -42,8 +44,14 @@ export function useServerMutation<TData, TVariables = unknown>(
: error.response.data;
if (errorData?.error === "SESSION_REFRESH_REQUIRED") {
const currentUrl = window.location.pathname + window.location.search;
window.location.href = `/refresh-session?redirect=${encodeURIComponent(currentUrl)}`;
if (!isMutationRefreshingSession) {
isMutationRefreshingSession = true;
const currentUrl = window.location.pathname + window.location.search;
setTimeout(() => {
isMutationRefreshingSession = false;
}, 1000);
window.location.href = `/refresh-session?redirect=${encodeURIComponent(currentUrl)}`;
}
throw new Error("SESSION_REFRESH_REQUIRED");
}
} catch (parseError) {}