Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

fix(nuxt3): return error page on blocked initial navigation #3201

Merged
merged 7 commits into from Feb 14, 2022
26 changes: 20 additions & 6 deletions packages/nuxt3/src/pages/runtime/router.ts
Expand Up @@ -6,6 +6,7 @@ import {
RouterLink,
NavigationGuard
} from 'vue-router'
import { createError } from 'h3'
import NuxtPage from './page'
import NuxtLayout from './layout'
import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig } from '#app'
Expand Down Expand Up @@ -93,6 +94,15 @@ export default defineNuxtPlugin((nuxtApp) => {
}

const result = await callWithNuxt(nuxtApp, middleware, [to, from])
if (process.server) {
if (result === false || result instanceof Error) {
const error = result || createError({
statusMessage: `Route navigation aborted: ${nuxtApp.ssrContext.url}`
})
nuxtApp.ssrContext.error = error
throw error
}
}
if (result || result === false) { return result }
}
})
Expand All @@ -112,13 +122,17 @@ export default defineNuxtPlugin((nuxtApp) => {
})
}

await router.isReady()
try {
await router.isReady()

const is404 = router.currentRoute.value.matched.length === 0
if (process.server && is404) {
const error = new Error(`Page not found: ${nuxtApp.ssrContext.url}`)
// @ts-ignore
error.statusCode = 404
const is404 = router.currentRoute.value.matched.length === 0
if (process.server && is404) {
throw createError({
statusCode: 404,
statusMessage: `Page not found: ${nuxtApp.ssrContext.url}`
})
}
} catch (error) {
nuxtApp.ssrContext.error = error
}
})
Expand Down