Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix authState getting wiped on page reload on static websites #712

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/runtime/composables/local/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { getRequestURLWN } from '../../utils/callWithNuxt'
import { useAuthState } from './useAuthState'
// @ts-expect-error - #auth not defined
import type { SessionData } from '#auth'
import { useNuxtApp, useRuntimeConfig, nextTick, navigateTo } from '#imports'
import { useCookie, useNuxtApp, useRuntimeConfig, nextTick, navigateTo } from '#imports'

type Credentials = { username?: string, email?: string, password?: string } & Record<string, any>

Expand Down Expand Up @@ -82,16 +82,28 @@ const getSession: GetSessionFunc<SessionData | null | void> = async (getSessionO

const headers = new Headers(token.value ? { [config.token.headerName]: token.value } as HeadersInit : undefined)

const sessionCookie = useCookie<Object | null>('auth:sessionCookie', {
default: () => null,
maxAge: config.token.maxAgeInSeconds,
sameSite: config.token.sameSiteAttribute
})

loading.value = true
try {
data.value = await _fetch<SessionData>(nuxt, path, { method, headers })
// Store the session data as a cookie
lastRefreshedAt.value = new Date()
sessionCookie.value = {
lastRefreshedAt: lastRefreshedAt.value,
data: data.value
}
} catch {
// Clear all data: Request failed so we must not be authenticated
data.value = null
rawToken.value = null
sessionCookie.value = null
}
loading.value = false
lastRefreshedAt.value = new Date()

const { required = false, callbackUrl, onUnauthenticated, external } = getSessionOptions ?? {}
if (required && data.value === null) {
Expand Down
27 changes: 25 additions & 2 deletions src/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { getHeader } from 'h3'
import authMiddleware from './middleware/auth'
import { addRouteMiddleware, defineNuxtPlugin, useRuntimeConfig, useAuth, useAuthState } from '#imports'
import { useTypedBackendConfig } from './helpers'
import type { SessionCookie } from './types'
import { addRouteMiddleware, defineNuxtPlugin, useRuntimeConfig, useAuth, useAuthState, useCookie } from '#imports'

export default defineNuxtPlugin(async (nuxtApp) => {
// 1. Initialize authentication state, potentially fetch current session
const { data, lastRefreshedAt } = useAuthState()
const { data, lastRefreshedAt, rawToken, loading } = useAuthState()
const { getSession } = useAuth()

// use runtimeConfig
Expand All @@ -19,6 +21,27 @@ export default defineNuxtPlugin(async (nuxtApp) => {

// Only fetch session if it was not yet initialized server-side
if (typeof data.value === 'undefined' && !nitroPrerender) {
// Restore the session data from the cookie
const config = useTypedBackendConfig(useRuntimeConfig(), 'local')
const sessionCookie = useCookie<SessionCookie | null>('auth:sessionCookie')
const cookieToken = useCookie<string | null>(config.token.cookieName)
if (sessionCookie.value && !rawToken.value && cookieToken.value) {
try {
loading.value = true
const sessionData = sessionCookie.value
lastRefreshedAt.value = sessionData?.lastRefreshedAt
data.value = sessionData?.data
rawToken.value = cookieToken.value
} catch (error) {
console.error('Failed to parse session data from cookie:', error)
} finally {
loading.value = false
}
}

if (!data.value) {
await getSession()
}
await getSession()
}

Expand Down
4 changes: 4 additions & 0 deletions src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,10 @@ export interface ModuleOptionsNormalized extends ModuleOptions {
fullBaseUrl: string
}
}
export interface SessionCookie {
lastRefreshedAt?: SessionLastRefreshedAt
data?: SessionDataObject
}

// Augment types
declare module 'nuxt/schema' {
Expand Down
Loading