Skip to content

Open source personal finance application

fix: refactor Convex auth to use convexClient plugin and fix post-login timing race

Ilya Komichev436fc087b0ba
diff --git a/app/app.vue b/app/app.vue
index ea3a46ac..5350c08b 100644
--- a/app/app.vue
+++ b/app/app.vue
@@ -38,7 +38,6 @@ useHead({
{ content: 'width=device-width, initial-scale=1, viewport-fit=cover', name: 'viewport' },
{ content: color, key: 'theme-color', name: 'theme-color' },
],
- noscript: [{ innerHTML: 'This website requires JavaScript.' }],
style: [
{ id: 'nuxt-ui-black-as-primary', innerHTML: blackAsPrimary, tagPriority: -2 },
{ id: 'nuxt-ui-radius', innerHTML: radius, tagPriority: -2 },
@@ -60,8 +59,8 @@ useGuard()
<NuxtLoadingIndicator :height="2" color="var(--ui-primary)" />
<NuxtPwaManifest />
- <NuxtLayout>
- <NuxtPage />
+ <NuxtLayout v-slot="{ keepalive }">
+ <NuxtPage :keepalive="keepalive" />
</NuxtLayout>
</UApp>
</template>
diff --git a/app/components/app/useInitApp.ts b/app/components/app/useInitApp.ts
index 3f43d857..2b129c49 100644
--- a/app/components/app/useInitApp.ts
+++ b/app/components/app/useInitApp.ts
@@ -78,6 +78,11 @@ export function useInitApp() {
// Unblock persists — may have been blocked by a prior clearLocalData
unblockPersist()
+ // Wait for Convex auth token to be fetched so queries run authenticated.
+ // Without this, queries can fire before setAuth's token fetch completes.
+ const { $waitForConvexAuth } = useNuxtApp()
+ await ($waitForConvexAuth as () => Promise<void>)()
+
// Set in-memory userId for queue ownership stamping during pushes
setOfflineQueueUserId(userStore.uid)
diff --git a/app/composables/useAuth.ts b/app/composables/useAuth.ts
index 4934959b..b040ceb4 100644
--- a/app/composables/useAuth.ts
+++ b/app/composables/useAuth.ts
@@ -1,7 +1,17 @@
-import { crossDomainClient } from '@convex-dev/better-auth/client/plugins'
+import { convexClient, crossDomainClient } from '@convex-dev/better-auth/client/plugins'
import { createAuthClient } from 'better-auth/vue'
-type AuthClient = ReturnType<typeof createAuthClient>
+function createClient(siteUrl: string) {
+ return createAuthClient({
+ baseURL: siteUrl,
+ plugins: [
+ convexClient(),
+ crossDomainClient(),
+ ],
+ })
+}
+
+type AuthClient = ReturnType<typeof createClient>
export function useAuth(): AuthClient {
const nuxtApp = useNuxtApp() as { _authClient?: AuthClient } & ReturnType<typeof useNuxtApp>
@@ -9,13 +19,7 @@ export function useAuth(): AuthClient {
if (!nuxtApp._authClient) {
const config = useRuntimeConfig()
const siteUrl = config.public.convexSiteUrl as string
-
- nuxtApp._authClient = createAuthClient({
- baseURL: siteUrl,
- plugins: [
- crossDomainClient(),
- ],
- })
+ nuxtApp._authClient = createClient(siteUrl)
}
return nuxtApp._authClient
diff --git a/app/layouts/default.vue b/app/layouts/default.vue
index 1b718d8b..4d336a8b 100644
--- a/app/layouts/default.vue
+++ b/app/layouts/default.vue
@@ -39,9 +39,6 @@ const { error, status } = useAsyncData(
loadDataFromDB()
}
},
- {
- lazy: true,
- },
)
defineShortcuts({
@@ -102,10 +99,6 @@ defineShortcuts({
</template>
</template>
- <div v-else class="fixed inset-0 flex items-center justify-center">
- <UiLogo class="!text-6xl" />
- </div>
-
<Teleport
v-if="categoriesStore.hasItems && walletsStore.hasItems"
to="body"
diff --git a/app/pages/auth/callback.vue b/app/pages/auth/callback.vue
index 99b6322f..fa8d85d6 100644
--- a/app/pages/auth/callback.vue
+++ b/app/pages/auth/callback.vue
@@ -54,11 +54,14 @@ onMounted(async () => {
setAuthCookie(uid)
+ // Set Convex auth BEFORE navigating so that loadDataFromDB()
+ // queries are queued behind the token fetch (WebSocket pauses).
+ const { $ensureConvexAuth } = useNuxtApp()
+ ;($ensureConvexAuth as () => void)()
+
const redirectTo = getSafeRedirectPath(localStorage.getItem('finapp.authRedirect'))
localStorage.removeItem('finapp.authRedirect')
- // SPA navigation — the Convex plugin's session watch detects the
- // auth transition and calls client.setAuth(fetchToken) automatically.
navigateTo(redirectTo, { replace: true })
return
}
diff --git a/app/plugins/convex.ts b/app/plugins/convex.ts
index c87202d1..c4401d8b 100644
--- a/app/plugins/convex.ts
+++ b/app/plugins/convex.ts
@@ -16,89 +16,50 @@ export default defineNuxtPlugin(() => {
const authClient = useAuth()
const session = authClient.useSession()
- const siteUrl = config.public.convexSiteUrl as string
-
- const fetchConvexToken = async (forceRefreshToken: boolean) => {
- const controller = new AbortController()
- const timeout = setTimeout(() => controller.abort(), 10000)
+ // Resolves when the first token fetch completes (success or failure).
+ // Consumers (loadDataFromDB) await this before issuing Convex queries
+ // to ensure the WebSocket is authenticated.
+ let authReadyResolve: (() => void) | null = null
+ let authReadyPromise: Promise<void> | null = null
+
+ // Fetch a Convex JWT via Better Auth's /convex/token endpoint.
+ // The crossDomainClient plugin automatically handles cookie forwarding
+ // (reads localStorage['better-auth_cookie'] → sends as Better-Auth-Cookie header).
+ const fetchToken = async (opts: { forceRefreshToken: boolean }) => {
+ if (!hasAuthCookie()) {
+ authReadyResolve?.()
+ return null
+ }
try {
- // Use raw fetch with explicit cookie forwarding — cross-domain
- // client stores cookies in localStorage, not document.cookie.
- const raw = localStorage.getItem('better-auth_cookie')
- if (!raw)
- return null
-
- let parsed: Record<string, { value?: string }>
- try {
- parsed = JSON.parse(raw)
- }
- catch {
- return null
- }
-
- if (!parsed || typeof parsed !== 'object')
- return null
- const cookieStr = Object.entries(parsed)
- .filter(([, val]) => val?.value)
- .map(([key, val]) => `${key}=${val!.value}`)
- .join('; ')
-
- if (!cookieStr)
- return null
-
- // disableRefresh is set by the before hook in convex/auth.ts for /convex/token.
- const url = new URL('/api/auth/convex/token', siteUrl)
- if (forceRefreshToken)
- url.searchParams.set('forceRefresh', 'true')
-
- const res = await fetch(url, {
- credentials: 'omit',
- headers: {
- 'Better-Auth-Cookie': cookieStr,
- },
- method: 'GET',
- signal: controller.signal,
- })
-
- if (!res.ok) {
- logger.error(`convex/token ${res.status}`, { cookieKeys: Object.keys(parsed), hasCookie: !!cookieStr })
- return null
- }
-
- const data = await res.json()
- return data?.token ?? null
+ const { data } = await authClient.convex.token()
+ const token = data?.token || null
+ authReadyResolve?.()
+ return token
}
catch (error) {
logger.error('fetchConvexToken error:', error)
+ authReadyResolve?.()
return null
}
- finally {
- clearTimeout(timeout)
- }
}
- const fetchToken = async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
- if (!hasAuthCookie())
- return null
-
- return fetchConvexToken(forceRefreshToken)
+ function startAuth() {
+ if (!authReadyPromise) {
+ authReadyPromise = new Promise<void>((resolve) => {
+ authReadyResolve = resolve
+ })
+ }
+ client.setAuth(fetchToken)
}
// Eagerly set auth when the user has a cached auth cookie.
- //
- // This is NOT SSR heritage — it is required for SPA mode too.
- // The auth middleware calls getSession() in the background (non-blocking),
- // so the useSession() reactive ref is still pending when stores start
- // querying Convex in default.vue's useAsyncData. Without this eager
- // setAuth, those queries would fire with no auth token → 401 errors.
- //
// hasAuthCookie() is a fast synchronous document.cookie check that lets
// us call setAuth immediately, which starts token fetching in parallel
// with the background session resolution.
let authSet = false
if (hasAuthCookie()) {
- client.setAuth(fetchToken)
+ startAuth()
authSet = true
}
@@ -111,9 +72,8 @@ export default defineNuxtPlugin(() => {
if (resolvedUid === undefined)
return // still pending
if (resolvedUid) {
- // Only call setAuth on actual transition (login), not on every session refresh
if (!authSet) {
- client.setAuth(fetchToken)
+ startAuth()
authSet = true
}
}
@@ -125,9 +85,27 @@ export default defineNuxtPlugin(() => {
},
)
+ // Called from callback page after login to ensure Convex auth is set
+ // BEFORE SPA navigation to dashboard. Without this, loadDataFromDB()
+ // fires queries before the plugin's session watch triggers setAuth.
+ function ensureConvexAuth() {
+ if (hasAuthCookie()) {
+ startAuth()
+ authSet = true
+ }
+ }
+
+ // Returns a promise that resolves once the Convex auth token has been
+ // fetched (or immediately if no auth is in progress).
+ function waitForAuth(): Promise<void> {
+ return authReadyPromise ?? Promise.resolve()
+ }
+
return {
provide: {
convex: client,
+ ensureConvexAuth,
+ waitForConvexAuth: waitForAuth,
},
}
})
diff --git a/convex/categories.test.ts b/convex/categories.test.ts
index 7261021c..8cbfdebf 100644
--- a/convex/categories.test.ts
+++ b/convex/categories.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'
-import { modules } from './test-utils/setup'
+import { modules } from './test_utils/setup.helper'
const validCategory = {
color: '#ff0000',
diff --git a/convex/schema.ts b/convex/schema.ts
index 532bb18c..3884be6c 100644
--- a/convex/schema.ts
+++ b/convex/schema.ts
@@ -5,6 +5,7 @@ import { TrnType, walletTypeValidator } from './validators'
export default defineSchema({
categories: defineTable({
+ childIds: v.optional(v.array(v.id('categories'))),
color: v.string(),
icon: v.string(),
name: v.string(),
diff --git a/convex/test-utils/setup.ts b/convex/test_utils/setup.helper.ts
similarity index 100%
rename from convex/test-utils/setup.ts
rename to convex/test_utils/setup.helper.ts
diff --git a/convex/trns.test.ts b/convex/trns.test.ts
index d0b47276..b3cde71a 100644
--- a/convex/trns.test.ts
+++ b/convex/trns.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'
-import { modules, setMockUser } from './test-utils/setup'
+import { modules, setMockUser } from './test_utils/setup.helper'
const validWallet = {
color: '#000',
diff --git a/convex/trns.ts b/convex/trns.ts
index f741b71f..21eeffe7 100644
--- a/convex/trns.ts
+++ b/convex/trns.ts
@@ -70,7 +70,9 @@ export const delta = query({
export const ensureSyncMeta = mutation({
args: {},
handler: async (ctx) => {
- const user = await requireAuthUser(ctx)
+ const user = await getAuthUser(ctx)
+ if (!user)
+ return
const existing = await ctx.db
.query('syncMeta')
.withIndex('by_user', q => q.eq('userId', user._id))
diff --git a/convex/wallets.test.ts b/convex/wallets.test.ts
index 006ad2b5..d15760f2 100644
--- a/convex/wallets.test.ts
+++ b/convex/wallets.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'
-import { modules, setMockUser } from './test-utils/setup'
+import { modules, setMockUser } from './test_utils/setup.helper'
const validWallet = {
color: '#ff0000',
diff --git a/nuxt.config.ts b/nuxt.config.ts
index 9628ca38..13300201 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -88,6 +88,14 @@ export default defineNuxtConfig({
'@nuxt/eslint',
],
+ // Pre-render the SPA shell so the service worker can precache it
+ // for offline navigation (navigateFallback: '/')
+ nitro: {
+ prerender: {
+ routes: ['/'],
+ },
+ },
+
pages: {
pattern: ['**/*.vue', '!**/_/**'],
},
diff --git a/vitest.config.ts b/vitest.config.ts
index b46084dd..549e1926 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -36,7 +36,7 @@ export default defineConfig({
environment: 'edge-runtime',
include: ['convex/**/*.test.ts'],
name: 'convex',
- setupFiles: ['./convex/test-utils/setup.ts'],
+ setupFiles: ['./convex/test_utils/setup.helper.ts'],
},
},
],