Open source personal finance application
feat(convex): implement session token retrieval for cross-domain authentication
Ilya Komichev6e9efcf405da
diff --git a/app/middleware/auth.global.ts b/app/middleware/auth.global.tsindex ed0768b2..efc0fca0 100644--- a/app/middleware/auth.global.ts+++ b/app/middleware/auth.global.ts@@ -4,6 +4,11 @@ import { createLogger } from '~/utils/logger'const logger = createLogger('auth/middleware')+// Track whether we've already initialized the cross-domain session+// to avoid calling getSession() on every navigation (which triggers+// $sessionSignal → useSession refetch → get-session → signal → loop)+let sessionInitialized = false+export default defineNuxtRouteMiddleware(async (to) => {// Skip auth during static prerender — no session context availableif (import.meta.prerender)@@ -56,15 +61,19 @@ export default defineNuxtRouteMiddleware(async (to) => {const isLoginPage = to.path === '/login'// Has cached auth: let user through immediately, initialize session in background.- // The getSession() call is needed to establish the cross-domain session+ // The getSession() call is needed once to establish the cross-domain session// so that useSession() reactive ref updates in the app.- // On network errors (offline) — do nothing, let the user work with cached data.- // On invalid session (server says no user) — clear cookie and redirect to login.+ // Only call once per page load — repeated calls trigger $sessionSignal loop+ // in the cross-domain client (each response sets a cookie → signal → refetch).if (hasAuthCookie()) {- authClient.getSession()- .catch((error) => {- logger.error('Background getSession failed:', error)- })+ if (!sessionInitialized) {+ sessionInitialized = true+ authClient.getSession()+ .catch((error) => {+ logger.error('Background getSession failed:', error)+ sessionInitialized = false+ })+ }if (isLoginPage) {return navigateTo('/dashboard')diff --git a/app/plugins/convex.ts b/app/plugins/convex.tsindex 76723d3b..5a835ebd 100644--- a/app/plugins/convex.ts+++ b/app/plugins/convex.ts@@ -30,12 +30,38 @@ export default defineNuxtPlugin(() => {const authClient = useAuth()const session = authClient.useSession()+ /**+ * Read the signed session token from cross-domain client's localStorage.+ * We send it as Authorization: Bearer to bypass the Better-Auth-Cookie+ * flow which fails for /convex/token (cross-domain before-hook doesn't+ * inject cookies into the Cookie header reliably for this endpoint).+ */+ function getSessionToken(): string | null {+ try {+ const raw = localStorage.getItem('better-auth_cookie')+ if (!raw)+ return null+ const cookies = JSON.parse(raw) as Record<string, { value?: string }>+ for (const [key, val] of Object.entries(cookies)) {+ if (key.includes('session_token') && val?.value) {+ return val.value+ }+ }+ return null+ }+ catch {+ return null+ }+ }+const fetchConvexToken = async (forceRefreshToken: boolean) => {const controller = new AbortController()const timeout = setTimeout(() => controller.abort(), 5000)try {+ const sessionToken = getSessionToken()const { data } = await authClient.$fetch<{ token: string }>('/convex/token', {+ headers: sessionToken ? { Authorization: `Bearer ${sessionToken}` } : undefined,method: 'GET',query: forceRefreshToken ? { forceRefresh: 'true' } : undefined,signal: controller.signal,