From 187230b0c52e7f065ddd2c417713577785e9c27c Mon Sep 17 00:00:00 2001 From: Nicolas Payot Date: Wed, 14 Jun 2023 16:37:21 +0200 Subject: [PATCH] fix(nuxt): abort navigation when updating `window.location` (#21521) --- packages/nuxt/src/app/composables/router.ts | 13 ++++++++++++- test/bundle.test.ts | 2 +- 2 files changed, 13 insertions(+), 2 deletions(-) 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"')