diff --git a/packages/nuxt/src/pages/runtime/plugins/router.ts b/packages/nuxt/src/pages/runtime/plugins/router.ts index 8427831bd4..4efeb84616 100644 --- a/packages/nuxt/src/pages/runtime/plugins/router.ts +++ b/packages/nuxt/src/pages/runtime/plugins/router.ts @@ -198,7 +198,7 @@ const plugin: Plugin<{ router: Router }> = defineNuxtPlugin({ fatal: false, statusMessage: `Page not found: ${to.fullPath}` }))) - } else if (process.server && to.redirectedFrom) { + } else if (process.server && to.redirectedFrom && to.fullPath !== initialURL) { await nuxtApp.runWithContext(() => navigateTo(to.fullPath || '/')) } }) diff --git a/test/basic.test.ts b/test/basic.test.ts index cc28628073..60a94954f6 100644 --- a/test/basic.test.ts +++ b/test/basic.test.ts @@ -117,6 +117,11 @@ describe('pages', () => { expect(headers.get('location')).toEqual('/') }) + it('allows routes to be added dynamically', async () => { + const html = await $fetch('/add-route-test') + expect(html).toContain('Hello Nuxt 3!') + }) + it('includes page metadata from pages added in pages:extend hook', async () => { const res = await fetch('/page-extend') expect(res.headers.get('x-extend')).toEqual('added in pages:extend') diff --git a/test/fixtures/basic/plugins/add-route.ts b/test/fixtures/basic/plugins/add-route.ts new file mode 100644 index 0000000000..cdf5d47c98 --- /dev/null +++ b/test/fixtures/basic/plugins/add-route.ts @@ -0,0 +1,18 @@ +export default defineNuxtPlugin((_nuxtApp) => { + const router = useRouter() + + router.beforeEach((to) => { + if (to.path !== '/add-route-test') { return } + if (router.getRoutes().some(route => route.path === to.path)) { + return + } + + router.addRoute({ + path: to.path, + name: to.path, + component: () => import('~/pages/index.vue') + }) + + return to.path + }) +})