Skip to content

Open source personal finance application

refactor: switch from SSR to SPA mode with generateSW PWA strategy

Ilya Komichev8e46b30490fc
diff --git a/app/components/bottomSheet/BottomSheet.vue b/app/components/bottomSheet/BottomSheet.vue
index 90aaf440..2043d06f 100644
--- a/app/components/bottomSheet/BottomSheet.vue
+++ b/app/components/bottomSheet/BottomSheet.vue
@@ -47,7 +47,7 @@ const {
/**
* Body scroll lock
*/
-const isBodyLocked = import.meta.client ? useScrollLock(document.body) : ref(false)
+const isBodyLocked = useScrollLock(document.body)
/**
* Run init when mounted or isShow changed
diff --git a/app/components/offline/replay.ts b/app/components/offline/replay.ts
index c8452803..7ca873c9 100644
--- a/app/components/offline/replay.ts
+++ b/app/components/offline/replay.ts
@@ -27,9 +27,6 @@ async function collectRemaps(promises: (Promise<unknown> | undefined)[], remapId
}
export async function replayOfflineQueue(): Promise<void> {
- if (!import.meta.client)
- return
-
if (_isReplaying)
return
diff --git a/app/composables/useConvex.ts b/app/composables/useConvex.ts
index 9abe14cd..b5395bd0 100644
--- a/app/composables/useConvex.ts
+++ b/app/composables/useConvex.ts
@@ -1,19 +1,15 @@
-import type { ConvexClient, ConvexHttpClient } from 'convex/browser'
+import type { ConvexClient } from 'convex/browser'
import { api } from '~~/convex/_generated/api'
-export function useConvexClient(): ConvexClient | ConvexHttpClient {
+export function useConvexClient(): ConvexClient {
const { $convex } = useNuxtApp()
- return $convex as ConvexClient | ConvexHttpClient
-}
-
-export function useConvexClientComposable(): ConvexClient {
- return useConvexClient() as ConvexClient
+ return $convex as ConvexClient
}
export function useConvexClientWithApi() {
return {
api,
- client: useConvexClientComposable(),
+ client: useConvexClient(),
}
}
diff --git a/app/pages/auth/callback.vue b/app/pages/auth/callback.vue
index 060b85bd..99b6322f 100644
--- a/app/pages/auth/callback.vue
+++ b/app/pages/auth/callback.vue
@@ -22,7 +22,7 @@ onMounted(async () => {
if (hasAuthCookie()) {
const redirectTo = getSafeRedirectPath(localStorage.getItem('finapp.authRedirect'))
localStorage.removeItem('finapp.authRedirect')
- window.location.href = redirectTo
+ navigateTo(redirectTo, { replace: true })
return
}
@@ -57,9 +57,9 @@ onMounted(async () => {
const redirectTo = getSafeRedirectPath(localStorage.getItem('finapp.authRedirect'))
localStorage.removeItem('finapp.authRedirect')
- // Hard navigation creates a fresh app with the cookie already set.
- // This ensures Convex plugin initializes with auth from the start.
- window.location.href = redirectTo
+ // 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/pages/login.vue b/app/pages/login.vue
index cfeba542..e4438369 100644
--- a/app/pages/login.vue
+++ b/app/pages/login.vue
@@ -28,16 +28,6 @@ async function signInWithGoogle() {
isDemo.value = null
isLoading.value = true
- // Unregister service workers before OAuth flow.
- // A stale SW with navigateFallback intercepts the callback page navigation
- // at the network level and serves cached content instead of the real page.
- // Our OTT verification code never runs → auth fails on re-login.
- if ('serviceWorker' in navigator) {
- const registrations = await navigator.serviceWorker.getRegistrations()
- for (const reg of registrations)
- await reg.unregister()
- }
-
// Remember where user wanted to go, so callback page can redirect back.
// Using localStorage (synchronous) instead of cookie — cookie may not flush
// before signIn.social() triggers full-page navigation to Google.
diff --git a/app/plugins/convex.ts b/app/plugins/convex.ts
index 6118a451..c87202d1 100644
--- a/app/plugins/convex.ts
+++ b/app/plugins/convex.ts
@@ -1,6 +1,4 @@
-import type { ConvexClient, ConvexHttpClient } from 'convex/browser'
-
-import { createConvexClient, createConvexHttpClient } from '~~/services/convex/client'
+import { createConvexClient } from '~~/services/convex/client'
import { clearAuthCookie, hasAuthCookie } from '~/composables/useAuthCookie'
import { createLogger } from '~/utils/logger'
@@ -11,128 +9,125 @@ export default defineNuxtPlugin(() => {
const config = useRuntimeConfig()
const convexUrl = config.public.convexUrl as string
- if (!convexUrl) {
- if (import.meta.prerender)
- return
+ if (!convexUrl)
throw new Error('CONVEX_URL is not set in environment variables')
- }
- let convex: ConvexClient | ConvexHttpClient
+ const client = createConvexClient(convexUrl)
+ const authClient = useAuth()
+ const session = authClient.useSession()
- if (import.meta.server) {
- convex = createConvexHttpClient(convexUrl)
- }
- else {
- const client = createConvexClient(convexUrl)
- const authClient = useAuth()
- const session = authClient.useSession()
+ const siteUrl = config.public.convexSiteUrl as string
- const siteUrl = config.public.convexSiteUrl as string
+ const fetchConvexToken = async (forceRefreshToken: boolean) => {
+ const controller = new AbortController()
+ const timeout = setTimeout(() => controller.abort(), 10000)
- const fetchConvexToken = async (forceRefreshToken: boolean) => {
- const controller = new AbortController()
- const timeout = setTimeout(() => controller.abort(), 10000)
+ 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 {
- // 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 server-side by the before hook in convex/auth.ts
- // for /convex/token — no need to set it here.
- 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
+ parsed = JSON.parse(raw)
}
- catch (error) {
- logger.error('fetchConvexToken error:', error)
+ catch {
return null
}
- finally {
- clearTimeout(timeout)
- }
- }
- const fetchToken = async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
- if (!hasAuthCookie())
+ if (!parsed || typeof parsed !== 'object')
return null
+ const cookieStr = Object.entries(parsed)
+ .filter(([, val]) => val?.value)
+ .map(([key, val]) => `${key}=${val!.value}`)
+ .join('; ')
- return fetchConvexToken(forceRefreshToken)
- }
+ 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
+ }
- // Only set auth when user is logged in to avoid 401 in console
- let authSet = false
- if (hasAuthCookie()) {
- client.setAuth(fetchToken)
- authSet = true
+ const data = await res.json()
+ return data?.token ?? null
+ }
+ catch (error) {
+ logger.error('fetchConvexToken error:', error)
+ return null
+ }
+ finally {
+ clearTimeout(timeout)
}
+ }
- // Watch session state for auth transitions
- watch(
- () => session.value?.isPending === false
- ? (session.value?.data?.user?.id ?? null)
- : undefined,
- (resolvedUid) => {
- 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)
- authSet = true
- }
- }
- else {
- client.client.clearAuth()
- authSet = false
- clearAuthCookie()
- }
- },
- )
+ const fetchToken = async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
+ if (!hasAuthCookie())
+ return null
- convex = client
+ return fetchConvexToken(forceRefreshToken)
}
+ // 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)
+ authSet = true
+ }
+
+ // Watch session state for auth transitions
+ watch(
+ () => session.value?.isPending === false
+ ? (session.value?.data?.user?.id ?? null)
+ : undefined,
+ (resolvedUid) => {
+ 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)
+ authSet = true
+ }
+ }
+ else {
+ client.client.clearAuth()
+ authSet = false
+ clearAuthCookie()
+ }
+ },
+ )
+
return {
provide: {
- convex,
+ convex: client,
},
}
})
diff --git a/app/plugins/theme.ts b/app/plugins/theme.ts
index 86bff192..2b67bb4a 100644
--- a/app/plugins/theme.ts
+++ b/app/plugins/theme.ts
@@ -3,57 +3,30 @@ export default defineNuxtPlugin({
setup() {
const appConfig = useAppConfig()
- if (import.meta.client) {
- function updateColor(type: 'primary' | 'neutral') {
- const color = localStorage.getItem(`nuxt-ui-${type}`)
- if (color) {
- appConfig.ui.colors[type] = color
- }
+ function updateColor(type: 'primary' | 'neutral') {
+ const color = localStorage.getItem(`nuxt-ui-${type}`)
+ if (color) {
+ appConfig.ui.colors[type] = color
}
+ }
- function updateRadius() {
- const radius = localStorage.getItem('nuxt-ui-radius')
- if (radius) {
- appConfig.theme.radius = Number.parseFloat(radius)
- }
+ function updateRadius() {
+ const radius = localStorage.getItem('nuxt-ui-radius')
+ if (radius) {
+ appConfig.theme.radius = Number.parseFloat(radius)
}
+ }
- function updateBlackAsPrimary() {
- const blackAsPrimary = localStorage.getItem('nuxt-ui-black-as-primary')
- if (blackAsPrimary) {
- appConfig.theme.blackAsPrimary = blackAsPrimary === 'true'
- }
+ function updateBlackAsPrimary() {
+ const blackAsPrimary = localStorage.getItem('nuxt-ui-black-as-primary')
+ if (blackAsPrimary) {
+ appConfig.theme.blackAsPrimary = blackAsPrimary === 'true'
}
-
- updateColor('primary')
- updateColor('neutral')
- updateRadius()
- updateBlackAsPrimary()
}
- if (import.meta.server) {
- useHead({
- script: [{
- innerHTML: `
- (function(){
- var ls=localStorage,s=document.querySelector.bind(document);
- var pc=ls.getItem('nuxt-ui-primary'),nc=ls.getItem('nuxt-ui-neutral');
- if(pc||nc){
- var el=s('style#nuxt-ui-colors'),h=el.innerHTML;
- if(pc&&pc!=='black')h=h.replace(/(--ui-color-primary-\\d{2,3}:\\s*var\\(--color-)${appConfig.ui.colors.primary}(-\\d{2,3}.*?\\))/g,'$1'+pc+'$2');
- if(nc)h=h.replace(/(--ui-color-neutral-\\d{2,3}:\\s*var\\(--color-)${appConfig.ui.colors.neutral}(-\\d{2,3}.*?\\))/g,'$1'+(nc==='neutral'?'old-neutral':nc)+'$2');
- el.innerHTML=h;
- }
- var r=ls.getItem('nuxt-ui-radius');
- if(r)s('style#nuxt-ui-radius').innerHTML=':root{--ui-radius:'+r+'rem}';
- var b=ls.getItem('nuxt-ui-black-as-primary');
- s('style#nuxt-ui-black-as-primary').innerHTML=b==='true'?':root{--ui-primary:black}.dark{--ui-primary:white}':'';
- })()
- `.replace(/\s+/g, ' '),
- tagPriority: -1,
- type: 'text/javascript',
- }],
- })
- }
+ updateColor('primary')
+ updateColor('neutral')
+ updateRadius()
+ updateBlackAsPrimary()
},
})
diff --git a/app/sw.ts b/app/sw.ts
deleted file mode 100644
index 9ee7df44..00000000
--- a/app/sw.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { clientsClaim } from 'workbox-core'
-import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching'
-import { NavigationRoute, registerRoute, setCatchHandler } from 'workbox-routing'
-import { CacheFirst, StaleWhileRevalidate } from 'workbox-strategies'
-
-declare let self: ServiceWorkerGlobalScope
-
-self.skipWaiting()
-clientsClaim()
-
-// Precache static assets (JS, CSS, fonts, images) immediately on install
-precacheAndRoute(self.__WB_MANIFEST)
-cleanupOutdatedCaches()
-
-// Only cache 200 OK responses (skip redirects, opaque, error responses)
-const cacheOkOnly = {
- cacheWillUpdate: async ({ response }: { response: Response }) =>
- response.status === 200 ? response : null,
-}
-
-// Navigation: serve cached HTML instantly, update in background
-registerRoute(new NavigationRoute(new StaleWhileRevalidate({
- cacheName: 'pages',
- plugins: [cacheOkOnly],
-})))
-
-// i18n locale messages: serve cached, update in background
-registerRoute(
- ({ url }) => url.pathname.startsWith('/_i18n/'),
- new StaleWhileRevalidate({ cacheName: 'i18n', plugins: [cacheOkOnly] }),
-)
-
-// Runtime caching for external resources
-for (const origin of [
- 'https://api.iconify.design',
- 'https://fonts.googleapis.com',
- 'https://fonts.gstatic.com',
-]) {
- registerRoute(({ url }) => url.origin === origin, new CacheFirst())
-}
-
-// Prevent uncaught errors when network fails offline
-setCatchHandler(async () => Response.error())
diff --git a/nuxt.config.ts b/nuxt.config.ts
index 725edbb7..9628ca38 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -76,10 +76,6 @@ export default defineNuxtConfig({
clientBundle: {
collections: ['lucide', 'mdi'],
scan: true,
- ssr: true,
- },
- serverBundle: {
- collections: ['lucide', 'mdi'],
},
},
@@ -104,14 +100,7 @@ export default defineNuxtConfig({
devOptions: {
enabled: false,
navigateFallback: '/',
- navigateFallbackAllowlist: [/^\/$/],
suppressWarnings: false,
- type: 'module',
- },
- filename: 'sw.ts',
- injectManifest: {
- globIgnores: ['**/200*', '**/404*'],
- globPatterns: ['**/*.{js,json,css,html,png,svg,ico,woff2}'],
},
manifest: {
background_color: '#171717',
@@ -153,8 +142,31 @@ export default defineNuxtConfig({
theme_color: '#171717',
},
registerType: 'autoUpdate',
- srcDir: '.',
- strategies: 'injectManifest',
+ workbox: {
+ globIgnores: ['**/200*', '**/404*'],
+ globPatterns: ['**/*.{js,json,css,html,png,svg,ico,woff2}'],
+ navigateFallback: '/',
+ runtimeCaching: [
+ {
+ handler: 'CacheFirst',
+ options: {
+ cacheableResponse: { statuses: [0, 200] },
+ cacheName: 'iconify',
+ expiration: { maxEntries: 500 },
+ },
+ urlPattern: /^https:\/\/api\.iconify\.design\/.*/,
+ },
+ {
+ handler: 'CacheFirst',
+ options: {
+ cacheableResponse: { statuses: [0, 200] },
+ cacheName: 'google-fonts',
+ expiration: { maxEntries: 30 },
+ },
+ urlPattern: /^https:\/\/fonts\.(googleapis|gstatic)\.com\/.*/,
+ },
+ ],
+ },
},
runtimeConfig: {
@@ -164,6 +176,6 @@ export default defineNuxtConfig({
},
},
- ssr: true,
+ ssr: false,
telemetry: false,
})
diff --git a/services/convex/client.ts b/services/convex/client.ts
index 52ffc057..43338426 100644
--- a/services/convex/client.ts
+++ b/services/convex/client.ts
@@ -1,16 +1,9 @@
-import { ConvexClient, ConvexHttpClient } from 'convex/browser'
+import { ConvexClient } from 'convex/browser'
let clientInstance: ConvexClient | null = null
-let httpClientInstance: ConvexHttpClient | null = null
export function createConvexClient(url: string): ConvexClient {
if (!clientInstance)
clientInstance = new ConvexClient(url)
return clientInstance
}
-
-export function createConvexHttpClient(url: string): ConvexHttpClient {
- if (!httpClientInstance)
- httpClientInstance = new ConvexHttpClient(url)
- return httpClientInstance
-}
diff --git a/vite.config.ts b/vite.config.ts
index e685abfe..1f4677aa 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,9 +1,6 @@
import { defineConfig } from 'vite'
export default defineConfig({
- define: {
- 'import.meta.client': true,
- },
resolve: {
alias: {
'~/': '/app/',