From 3589a2d55f89664cf0bd04c0b65654a162565c21 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 14 Feb 2022 14:18:07 +0000 Subject: [PATCH] fix(nuxt3): return error page on blocked initial navigation (#3201) --- packages/nuxt3/src/pages/runtime/router.ts | 26 +++++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/packages/nuxt3/src/pages/runtime/router.ts b/packages/nuxt3/src/pages/runtime/router.ts index 246f303c2d..c1ccec61c4 100644 --- a/packages/nuxt3/src/pages/runtime/router.ts +++ b/packages/nuxt3/src/pages/runtime/router.ts @@ -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' @@ -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 } } }) @@ -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 } })