Skip to content

Open source personal finance application

feat: add offline support and session initialization tracking

Ilya Komichev0bb22b6c1f50
diff --git a/app/components/app/useInitApp.ts b/app/components/app/useInitApp.ts
index e63f731d..3f43d857 100644
--- a/app/components/app/useInitApp.ts
+++ b/app/components/app/useInitApp.ts
@@ -15,12 +15,24 @@ import { createLogger } from '~/utils/logger'
export function useInitApp() {
const isDbLoading = ref(false)
+ const isOffline = ref(false)
const userStore = useUserStore()
const currenciesStore = useCurrenciesStore()
const walletsStore = useWalletsStore()
const categoriesStore = useCategoriesStore()
const trnsStore = useTrnsStore()
+ // Sync data when coming back online
+ useEventListener(window, 'online', () => {
+ isOffline.value = false
+ if (userStore.uid && !isDbLoading.value)
+ loadDataFromDB()
+ })
+
+ useEventListener(window, 'offline', () => {
+ isOffline.value = true
+ })
+
async function loadDataFromCache() {
const [user, userSettings, currencies, categories, wallets, trns] = await Promise.all([
localforage.getItem(STORAGE_KEYS.user),
@@ -92,6 +104,7 @@ export function useInitApp() {
return {
clearLocalData,
isDbLoading,
+ isOffline,
loadDataFromCache,
loadDataFromDB,
}
diff --git a/app/components/user/useGuard.ts b/app/components/user/useGuard.ts
index 1aebdc94..acb0d554 100644
--- a/app/components/user/useGuard.ts
+++ b/app/components/user/useGuard.ts
@@ -12,10 +12,7 @@ export function useGuard() {
watch(
() => userStore.currentUser,
(user, prevUser) => {
- if (user && route.path === '/login') {
- router.push('/dashboard')
- }
- else if (prevUser && !user) {
+ if (prevUser && !user) {
if (userStore.isSigningOut)
return
clearLocalData()
diff --git a/app/components/user/useUserStore.ts b/app/components/user/useUserStore.ts
index 3bc6ac41..cebf1072 100644
--- a/app/components/user/useUserStore.ts
+++ b/app/components/user/useUserStore.ts
@@ -11,7 +11,7 @@ import { STORAGE_KEYS } from '~/components/offline/storageKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-import { clearAuthCookie } from '~/composables/useAuthCookie'
+import { clearAuthCookie, setSessionInitialized } from '~/composables/useAuthCookie'
import { blockPersist, handleMutationResult, isPersistBlocked } from '~/composables/useStoreSync'
import { createLogger } from '~/utils/logger'
@@ -170,6 +170,7 @@ export const useUserStore = defineStore('user', () => {
await localforage.clear()
isDemo.value = null
clearAuthCookie()
+ setSessionInitialized(false)
window.location.href = '/login'
return
}
@@ -190,6 +191,7 @@ export const useUserStore = defineStore('user', () => {
useTrnsFormStore().$reset()
setUser(null)
clearAuthCookie()
+ setSessionInitialized(false)
await localforage.clear()
await authClient.signOut()
}
diff --git a/app/composables/useAuthCookie.ts b/app/composables/useAuthCookie.ts
index 285bebd6..2e0b0861 100644
--- a/app/composables/useAuthCookie.ts
+++ b/app/composables/useAuthCookie.ts
@@ -1,3 +1,16 @@
+// 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 function isSessionInitialized(): boolean {
+ return _sessionInitialized
+}
+
+export function setSessionInitialized(value: boolean) {
+ _sessionInitialized = value
+}
+
export function hasAuthCookie(): boolean {
return document.cookie.includes('finapp.localAuthUid')
}
@@ -11,7 +24,3 @@ export function setAuthCookie(uid: string) {
export function clearAuthCookie() {
document.cookie = `finapp.localAuthUid=;path=/;max-age=0;SameSite=Lax${secureSuffix}`
}
-
-export function useAuthCookieSSR() {
- return useCookie('finapp.localAuthUid')
-}
diff --git a/app/layouts/default.vue b/app/layouts/default.vue
index 8390b4b1..1b718d8b 100644
--- a/app/layouts/default.vue
+++ b/app/layouts/default.vue
@@ -35,13 +35,12 @@ const { error, status } = useAsyncData(
}
else if (userStore.currentUser || hasAuthCookie()) {
await loadDataFromCache()
- loadDataFromDB()
+ if (navigator.onLine)
+ loadDataFromDB()
}
-
},
{
lazy: true,
- server: false,
},
)
diff --git a/app/middleware/auth.global.test.ts b/app/middleware/auth.global.test.ts
index b55a9b7b..d485ff47 100644
--- a/app/middleware/auth.global.test.ts
+++ b/app/middleware/auth.global.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// ---------------------------------------------------------------------------
// Shared mock state (hoisted so vi.mock factories can reference them)
@@ -8,16 +8,28 @@ const {
getSessionMock,
hasAuthCookieMock,
isDemoRef,
+ isSessionInitializedMock,
navigateToMock,
setAuthCookieMock,
-} = vi.hoisted(() => ({
- clearAuthCookieMock: vi.fn(),
- getSessionMock: vi.fn(),
- hasAuthCookieMock: vi.fn(() => false),
- isDemoRef: { value: false },
- navigateToMock: vi.fn(),
- setAuthCookieMock: vi.fn(),
-}))
+ setSessionInitializedMock,
+} = vi.hoisted(() => {
+ let _sessionInitialized = false
+ const isSessionInitializedMock = vi.fn(() => _sessionInitialized)
+ const setSessionInitializedMock = vi.fn((value: boolean) => {
+ _sessionInitialized = value
+ })
+
+ return {
+ clearAuthCookieMock: vi.fn(),
+ getSessionMock: vi.fn(),
+ hasAuthCookieMock: vi.fn(() => false),
+ isDemoRef: { value: false },
+ isSessionInitializedMock,
+ navigateToMock: vi.fn(),
+ setAuthCookieMock: vi.fn(),
+ setSessionInitializedMock,
+ }
+})
// ---------------------------------------------------------------------------
// Module mocks
@@ -29,8 +41,9 @@ vi.mock('~/components/demo/useDemo', () => ({
vi.mock('~/composables/useAuthCookie', () => ({
clearAuthCookie: clearAuthCookieMock,
hasAuthCookie: hasAuthCookieMock,
+ isSessionInitialized: isSessionInitializedMock,
setAuthCookie: setAuthCookieMock,
- useAuthCookieSSR: () => ({ value: null }),
+ setSessionInitialized: setSessionInitializedMock,
}))
vi.mock('~/utils/logger', () => ({
@@ -42,6 +55,7 @@ vi.mock('~/utils/logger', () => ({
// ---------------------------------------------------------------------------
vi.stubGlobal('defineNuxtRouteMiddleware', (fn: any) => fn)
vi.stubGlobal('navigateTo', navigateToMock)
+vi.stubGlobal('navigator', { onLine: true })
vi.stubGlobal('useAuth', () => ({ getSession: getSessionMock }))
vi.stubGlobal('getSafeRedirectPath', (value: unknown) => {
if (typeof value === 'string' && value.startsWith('/') && !value.startsWith('//'))
@@ -63,21 +77,25 @@ async function flushPromises() {
type MiddlewareFn = (to: ReturnType<typeof createRoute>) => Promise<unknown>
+let middleware: MiddlewareFn
+
async function loadMiddleware(): Promise<MiddlewareFn> {
- const mod = await import('~/middleware/auth.global')
- return mod.default as MiddlewareFn
+ if (!middleware) {
+ const mod = await import('~/middleware/auth.global')
+ middleware = mod.default as MiddlewareFn
+ }
+ return middleware
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
-// Note: import.meta.prerender and import.meta.server are undefined in vitest,
-// so SSR/prerender code paths are not exercised. All tests cover client behavior.
+// SPA mode — all code paths are client-side.
describe('auth.global middleware', () => {
beforeEach(() => {
- vi.resetModules()
vi.clearAllMocks()
+ setSessionInitializedMock(false)
isDemoRef.value = false
hasAuthCookieMock.mockReturnValue(false)
})
@@ -284,4 +302,53 @@ describe('auth.global middleware', () => {
})
})
})
+
+ // --- Offline scenarios ---
+
+ describe('offline', () => {
+ beforeEach(() => {
+ vi.stubGlobal('navigator', { onLine: false })
+ })
+
+ afterEach(() => {
+ vi.stubGlobal('navigator', { onLine: true })
+ })
+
+ it('skips getSession when offline with cached cookie', async () => {
+ hasAuthCookieMock.mockReturnValue(true)
+ const middleware = await loadMiddleware()
+ const result = await middleware(createRoute('/dashboard'))
+
+ expect(getSessionMock).not.toHaveBeenCalled()
+ expect(navigateToMock).not.toHaveBeenCalled()
+ expect(result).toBeUndefined()
+ })
+
+ it('redirects /login to /dashboard when offline with cached cookie', async () => {
+ hasAuthCookieMock.mockReturnValue(true)
+ const middleware = await loadMiddleware()
+ await middleware(createRoute('/login'))
+
+ expect(navigateToMock).toHaveBeenCalledWith('/dashboard')
+ })
+
+ it('redirects to /login when offline without cached cookie', async () => {
+ const middleware = await loadMiddleware()
+ await middleware(createRoute('/settings'))
+
+ expect(getSessionMock).not.toHaveBeenCalled()
+ expect(navigateToMock).toHaveBeenCalledWith({
+ path: '/login',
+ query: { redirect: '/settings' },
+ })
+ })
+
+ it('passes through /login when offline without cached cookie', async () => {
+ const middleware = await loadMiddleware()
+ const result = await middleware(createRoute('/login'))
+
+ expect(navigateToMock).not.toHaveBeenCalled()
+ expect(result).toBeUndefined()
+ })
+ })
})
diff --git a/app/middleware/auth.global.ts b/app/middleware/auth.global.ts
index 5275e6b7..8c3f9909 100644
--- a/app/middleware/auth.global.ts
+++ b/app/middleware/auth.global.ts
@@ -1,19 +1,10 @@
import { useDemo } from '~/components/demo/useDemo'
-import { clearAuthCookie, hasAuthCookie, setAuthCookie, useAuthCookieSSR } from '~/composables/useAuthCookie'
+import { clearAuthCookie, hasAuthCookie, isSessionInitialized, setAuthCookie, setSessionInitialized } from '~/composables/useAuthCookie'
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 available
- if (import.meta.prerender)
- return
-
// OTT can arrive on any route (callbackURL is not always preserved).
// Redirect to /auth/callback which handles OTT verification on the client.
if (to.query.ott && to.path !== '/auth/callback') {
@@ -37,26 +28,6 @@ export default defineNuxtRouteMiddleware(async (to) => {
return
}
- // SSR: use cached cookie to avoid flash of login page
- if (import.meta.server) {
- const ssrCookie = useAuthCookieSSR()
- const isLoginPage = to.path === '/login'
- const hasCachedAuth = !!ssrCookie.value
-
- if (!hasCachedAuth && !isLoginPage) {
- const redirect = to.fullPath === '/' ? undefined : { redirect: to.fullPath }
- return navigateTo({
- path: '/login',
- query: redirect,
- })
- }
- if (hasCachedAuth && isLoginPage) {
- return navigateTo('/dashboard')
- }
- return
- }
-
- // Client: verify auth with Better Auth
const authClient = useAuth()
const isLoginPage = to.path === '/login'
@@ -66,21 +37,21 @@ export default defineNuxtRouteMiddleware(async (to) => {
// 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()) {
- if (!sessionInitialized) {
- sessionInitialized = true
+ if (!isSessionInitialized() && navigator.onLine) {
+ setSessionInitialized(true)
authClient.getSession()
.then((session) => {
const user = session.data?.user || null
if (!user) {
logger.error('Background getSession: session expired, redirecting to login')
- sessionInitialized = false
+ setSessionInitialized(false)
clearAuthCookie()
navigateTo('/login')
}
})
.catch((error) => {
logger.error('Background getSession failed:', error)
- sessionInitialized = false
+ setSessionInitialized(false)
})
}
@@ -94,6 +65,15 @@ export default defineNuxtRouteMiddleware(async (to) => {
if (isLoginPage)
return
+ // Offline without cached auth — can't verify, redirect to login
+ if (!navigator.onLine) {
+ const redirect = to.fullPath === '/' ? undefined : { redirect: to.fullPath }
+ return navigateTo({
+ path: '/login',
+ query: redirect,
+ })
+ }
+
// No cached auth: must verify (blocking)
try {
const session = await authClient.getSession()