diff --git a/packages/nuxt/src/pages/runtime/plugins/router.ts b/packages/nuxt/src/pages/runtime/plugins/router.ts index 5dcf1786ba..fccd8ff78a 100644 --- a/packages/nuxt/src/pages/runtime/plugins/router.ts +++ b/packages/nuxt/src/pages/runtime/plugins/router.ts @@ -9,7 +9,7 @@ import { createWebHistory, } from '#vue-router' import { createError } from 'h3' -import { isEqual, isSamePath, withoutBase } from 'ufo' +import { isEqual, withoutBase } from 'ufo' import type { PageMeta } from '../composables' @@ -139,6 +139,36 @@ const plugin: Plugin<{ router: Router }> = defineNuxtPlugin({ named: {}, } + const error = useError() + if (import.meta.client || !nuxtApp.ssrContext?.islandContext) { + router.afterEach(async (to, _from, failure) => { + delete nuxtApp._processingMiddleware + + if (import.meta.client && !nuxtApp.isHydrating && error.value) { + // Clear any existing errors + await nuxtApp.runWithContext(clearError) + } + if (failure) { + await nuxtApp.callHook('page:loading:end') + } + if (import.meta.server && failure?.type === 4 /* ErrorTypes.NAVIGATION_ABORTED */) { + return + } + if (to.matched.length === 0) { + await nuxtApp.runWithContext(() => showError(createError({ + statusCode: 404, + fatal: false, + statusMessage: `Page not found: ${to.fullPath}`, + data: { + path: to.fullPath, + }, + }))) + } else if (import.meta.server && to.redirectedFrom && to.fullPath !== initialURL) { + await nuxtApp.runWithContext(() => navigateTo(to.fullPath || '/')) + } + }) + } + try { if (import.meta.server) { await router.push(initialURL) @@ -228,34 +258,6 @@ const plugin: Plugin<{ router: Router }> = defineNuxtPlugin({ await nuxtApp.callHook('page:loading:end') }) - const error = useError() - router.afterEach(async (to, _from, failure) => { - delete nuxtApp._processingMiddleware - - if (import.meta.client && !nuxtApp.isHydrating && error.value) { - // Clear any existing errors - await nuxtApp.runWithContext(clearError) - } - if (failure) { - await nuxtApp.callHook('page:loading:end') - } - if (import.meta.server && failure?.type === 4 /* ErrorTypes.NAVIGATION_ABORTED */) { - return - } - if (to.matched.length === 0) { - await nuxtApp.runWithContext(() => showError(createError({ - statusCode: 404, - fatal: false, - statusMessage: `Page not found: ${to.fullPath}`, - data: { - path: to.fullPath, - }, - }))) - } else if (import.meta.server && to.fullPath !== initialURL && (to.redirectedFrom || !isSamePath(to.fullPath, initialURL))) { - await nuxtApp.runWithContext(() => navigateTo(to.fullPath || '/')) - } - }) - nuxtApp.hooks.hookOnce('app:created', async () => { try { // #4920, #4982