Skip to content

fix(#621): store the data promise to await in route middleware #1033

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions playground-local/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default defineNuxtConfig({
signUp: { path: '/signup', method: 'post' }
},
pages: {
login: '/'
login: '/login'
},
token: {
signInResponseTokenPointer: '/token/accessToken'
Expand All @@ -37,7 +37,7 @@ export default defineNuxtConfig({
// Whether to refresh the session every time the browser window is refocused.
enableOnWindowFocus: true,
// Whether to refresh the session every `X` milliseconds. Set this to `false` to turn it off. The session will only be refreshed if a session already exists.
enablePeriodically: 5000,
enablePeriodically: 30000,
// Custom refresh handler - uncomment to use
// handler: './config/AuthRefreshHandler'
},
Expand Down
14 changes: 14 additions & 0 deletions src/runtime/composables/commonAuthState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,19 @@ import { useState } from '#imports'
export function makeCommonAuthState<SessionData>() {
const data = useState<SessionData | undefined | null>('auth:data', () => undefined)

// Store non-hydratable promise in useState, promise would be skipped by JSON.stringify
const dataPromise = useState('auth:dataPromise', () => {
const holder = {
promise: undefined as Promise<SessionData> | undefined,
}

Object.defineProperty(holder, 'promise', {
enumerable: false
})

return holder
})

const hasInitialSession = computed(() => !!data.value)

// If session exists, initialize as already synced
Expand All @@ -30,6 +43,7 @@ export function makeCommonAuthState<SessionData>() {

return {
data,
dataPromise,
loading,
lastRefreshedAt,
status,
Expand Down
8 changes: 7 additions & 1 deletion src/runtime/composables/local/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export function useAuth(): UseAuthReturn {

const {
data,
dataPromise,
status,
lastRefreshedAt,
loading,
Expand Down Expand Up @@ -184,7 +185,10 @@ export function useAuth(): UseAuthReturn {

loading.value = true
try {
const result = await _fetch<any>(nuxt, path, { method, headers })
const promise = _fetch<any>(nuxt, path, { method, headers })
dataPromise.value.promise = promise

const result = await promise
const { dataResponsePointer: sessionDataResponsePointer } = config.session
data.value = jsonPointerGet<SessionData>(result, sessionDataResponsePointer)
}
Expand All @@ -197,7 +201,9 @@ export function useAuth(): UseAuthReturn {
data.value = null
rawToken.value = null
}

loading.value = false
dataPromise.value.promise = undefined
lastRefreshedAt.value = new Date()

const { required = false, callbackUrl, onUnauthenticated, external } = getSessionOptions ?? {}
Expand Down
23 changes: 21 additions & 2 deletions src/runtime/middleware/sidebase-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { isExternalUrl } from '../utils/url'
import { isProduction } from '../helpers'
import { ERROR_PREFIX } from '../utils/logger'
import { determineCallbackUrlForRouteMiddleware } from '../utils/callbackUrl'
import { defineNuxtRouteMiddleware, navigateTo, useAuth, useRuntimeConfig } from '#imports'
import { defineNuxtRouteMiddleware, navigateTo, useAuth, useAuthState, useRuntimeConfig } from '#imports'

type MiddlewareMeta = boolean | {
/**
Expand Down Expand Up @@ -37,7 +37,7 @@ declare module 'vue-router' {
}
}

export default defineNuxtRouteMiddleware((to) => {
export default defineNuxtRouteMiddleware(async (to) => {
// Normalize options. If `undefined` was returned, we need to skip middleware
const options = normalizeUserOptions(to.meta.auth)
if (!options) {
Expand All @@ -63,6 +63,25 @@ export default defineNuxtRouteMiddleware((to) => {
return
}

// Handle the possible loading state by awaiting the data promise
// https://github.com/sidebase/nuxt-auth/issues/621
if (status.value === 'loading') {
const { dataPromise } = useAuthState()

if (dataPromise.value.promise) {
try {
const data = await dataPromise.value.promise
if (data) {
// Data was successfully fetched - user is logged in
return
}
}
catch {
// an error occurred, proving that we need to continue with the redirect
}
}
}

// We do not want to block the login page when the local provider is used
if (authConfig.provider.type === 'local') {
const loginRoute: string | undefined = authConfig.provider.pages.login
Expand Down
1 change: 1 addition & 0 deletions src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ export interface CommonUseAuthReturn<SignIn, SignOut, SessionData> {

export interface CommonUseAuthStateReturn<SessionData> {
data: WrappedSessionData<SessionData>
dataPromise: Ref<{ promise?: Promise<SessionData> | undefined }>
loading: Ref<boolean>
lastRefreshedAt: Ref<SessionLastRefreshedAt>
status: ComputedRef<SessionStatus>
Expand Down