From b4c0f17776edf9d2c45c14459278b44cd2a5d980 Mon Sep 17 00:00:00 2001 From: Connor Roberts <32241825+murshex@users.noreply.github.com> Date: Wed, 18 Dec 2024 17:26:32 +0700 Subject: [PATCH] fix(nuxt): respect `replace` in middleware with `navigateTo` (#30283) --- packages/nuxt/src/app/composables/router.ts | 3 +++ test/bundle.test.ts | 4 ++-- test/nuxt/composables.test.ts | 12 ++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/nuxt/src/app/composables/router.ts b/packages/nuxt/src/app/composables/router.ts index 0814873ff0..3f95ffe8ec 100644 --- a/packages/nuxt/src/app/composables/router.ts +++ b/packages/nuxt/src/app/composables/router.ts @@ -152,6 +152,9 @@ export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: Na // Early redirect on client-side if (import.meta.client && !isExternal && inMiddleware) { + if (options?.replace) { + return typeof to === 'string' ? { path: to, replace: true } : { ...to, replace: true } + } return to } diff --git a/test/bundle.test.ts b/test/bundle.test.ts index d15e9ec9f2..fa71467805 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -21,8 +21,8 @@ describe.skipIf(process.env.SKIP_BUNDLE_SIZE === 'true' || process.env.ECOSYSTEM const [clientStats, clientStatsInlined] = await Promise.all((['.output', '.output-inline']) .map(outputDir => analyzeSizes(['**/*.js'], join(rootDir, outputDir, 'public')))) - expect.soft(roundToKilobytes(clientStats!.totalBytes)).toMatchInlineSnapshot(`"115k"`) - expect.soft(roundToKilobytes(clientStatsInlined!.totalBytes)).toMatchInlineSnapshot(`"115k"`) + expect.soft(roundToKilobytes(clientStats!.totalBytes)).toMatchInlineSnapshot(`"116k"`) + expect.soft(roundToKilobytes(clientStatsInlined!.totalBytes)).toMatchInlineSnapshot(`"116k"`) const files = new Set([...clientStats!.files, ...clientStatsInlined!.files].map(f => f.replace(/\..*\.js/, '.js'))) diff --git a/test/nuxt/composables.test.ts b/test/nuxt/composables.test.ts index bfb0eed5d1..bbb06f0f82 100644 --- a/test/nuxt/composables.test.ts +++ b/test/nuxt/composables.test.ts @@ -623,6 +623,18 @@ describe('routing utilities: `navigateTo`', () => { expect(() => navigateTo(url, { external: true })).toThrowError(`Cannot navigate to a URL with '${protocol}:' protocol.`) } }) + it('navigateTo should replace current navigation state if called within middleware', () => { + const nuxtApp = useNuxtApp() + nuxtApp._processingMiddleware = true + expect(navigateTo('/')).toMatchInlineSnapshot(`"/"`) + expect(navigateTo('/', { replace: true })).toMatchInlineSnapshot(` + { + "path": "/", + "replace": true, + } + `) + nuxtApp._processingMiddleware = false + }) }) describe('routing utilities: `resolveRouteObject`', () => {