diff --git a/packages/nuxt/src/app/composables/router.ts b/packages/nuxt/src/app/composables/router.ts index a0d9f8b39a..84be97eb2c 100644 --- a/packages/nuxt/src/app/composables/router.ts +++ b/packages/nuxt/src/app/composables/router.ts @@ -148,8 +148,9 @@ export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: Na const router = useRouter() + const nuxtApp = useNuxtApp() + if (process.server) { - const nuxtApp = useNuxtApp() if (nuxtApp.ssrContext) { const fullPath = typeof to === 'string' || isExternal ? toPath : router.resolve(to).fullPath || '/' const location = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, fullPath) @@ -183,6 +184,16 @@ export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: Na } else { location.href = toPath } + // Within in a Nuxt route middleware handler + if (inMiddleware) { + // Abort navigation when app is hydrated + if (!nuxtApp.isHydrating) { + return false + } + // When app is hydrating (i.e. on page load), we don't want to abort navigation as + // it would lead to a 404 error / page that's blinking before location changes. + return new Promise(() => {}) + } return Promise.resolve() } diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 0fe5069ce2..c533359d13 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -35,7 +35,7 @@ describe.skipIf(process.env.SKIP_BUNDLE_SIZE === 'true' || process.env.ECOSYSTEM it('default server bundle size', async () => { stats.server = await analyzeSizes(['**/*.mjs', '!node_modules'], serverDir) - expect(roundToKilobytes(stats.server.totalBytes)).toMatchInlineSnapshot('"61.9k"') + expect(roundToKilobytes(stats.server.totalBytes)).toMatchInlineSnapshot('"62.0k"') const modules = await analyzeSizes('node_modules/**/*', serverDir) expect(roundToKilobytes(modules.totalBytes)).toMatchInlineSnapshot('"2295k"')