N
Nuxtβ€’6mo ago
Looney

Showing A Loading Component In Nuxt SPA While Router Middleware Is Resolving

Hi, I have a Nuxt 3 SPA app (ssr: false), where I'm trying to show a loading component while my authentication router middleware is being resolved/awaiting. Here's my code:
// composables/useAppState.ts
const isLoaded = ref(false);

export default function useAppState() {
return {
isLoaded
}
}

// middleware/auth.global.ts
export default defineNuxtRouteMiddleware(async () => {
const { isLoaded } = useAppState()

// An empty promise for testing purposes
await new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 1000)
})

isLoaded.value = true
})

// app.vue
<script setup lang="ts">
const { isLoaded } = useAppState()
</script>

<template>
<LoadingComponent v-if="!isLoaded" />
<NuxtPage />
</template>
// composables/useAppState.ts
const isLoaded = ref(false);

export default function useAppState() {
return {
isLoaded
}
}

// middleware/auth.global.ts
export default defineNuxtRouteMiddleware(async () => {
const { isLoaded } = useAppState()

// An empty promise for testing purposes
await new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 1000)
})

isLoaded.value = true
})

// app.vue
<script setup lang="ts">
const { isLoaded } = useAppState()
</script>

<template>
<LoadingComponent v-if="!isLoaded" />
<NuxtPage />
</template>
The problem is that the <LoadingComponent> doesn't seem to be mounted before the router middleware is resolved. I thought it was only the pages rendered by <NuxtPage> that was blocked from rendered before any middlewares was resolved. Does anyone know how to achieve this? Any help is really appreciated πŸ™‚
3 Replies
Looney
Looneyβ€’6mo ago
Update: I just tried this with a normal Vue app (without Nuxt) and it works as expected, where the loading component is rendered before the router middleware is resolved I have tried using the SPA loading template option in Nuxt, but that template is hidden already once the app is hydrated and not when the page loads, so this really hurts the user experience of my app, as the user just sees a blank white page while the middleware is being resolved 😦
Unknown User
Unknown Userβ€’4mo ago
Message Not Public
Sign In & Join Server To View
Looney
Looneyβ€’4mo ago
The solution in my case, was to migrate from Nuxt to a simple Vue 3 app πŸ˜