diff --git a/packages/next/shared/lib/router/router.ts b/packages/next/shared/lib/router/router.ts index cf1180fd6766ee0..cda9125962a0719 100644 --- a/packages/next/shared/lib/router/router.ts +++ b/packages/next/shared/lib/router/router.ts @@ -1552,7 +1552,11 @@ export default class Router implements BaseRouter { query = Object.assign({}, routeInfo.query || {}, query) } - if (routeMatch && pathname !== parsed.pathname) { + const cleanedParsedPathname = hasBasePath(parsed.pathname) + ? removeBasePath(parsed.pathname) + : parsed.pathname + + if (routeMatch && pathname !== cleanedParsedPathname) { Object.keys(routeMatch).forEach((key) => { if (routeMatch && query[key] === routeMatch[key]) { delete query[key] diff --git a/test/e2e/middleware-base-path/app/pages/dynamic-routes/[routeName].js b/test/e2e/middleware-base-path/app/pages/dynamic-routes/[routeName].js new file mode 100644 index 000000000000000..1fe4784b683d4e2 --- /dev/null +++ b/test/e2e/middleware-base-path/app/pages/dynamic-routes/[routeName].js @@ -0,0 +1,11 @@ +import { useRouter } from 'next/router' + +export default function DynamicRoutes() { + const { query } = useRouter() + + return ( +
+

{query.routeName}

+
+ ) +} diff --git a/test/e2e/middleware-base-path/app/pages/index.js b/test/e2e/middleware-base-path/app/pages/index.js index bc2fa5dd30667ed..02138dd7460d095 100644 --- a/test/e2e/middleware-base-path/app/pages/index.js +++ b/test/e2e/middleware-base-path/app/pages/index.js @@ -27,6 +27,11 @@ export default function Main({ message }) { redirect me to about +
  • + + Hello World + +
  • ) diff --git a/test/e2e/middleware-base-path/test/index.test.ts b/test/e2e/middleware-base-path/test/index.test.ts index 2b8ebcb8f87834d..dffe7a1e7963eca 100644 --- a/test/e2e/middleware-base-path/test/index.test.ts +++ b/test/e2e/middleware-base-path/test/index.test.ts @@ -35,4 +35,14 @@ describe('Middleware base tests', () => { const $ = cheerio.load(html) expect($('.title').text()).toBe('About Page') }) + it('router.query must exist when Link clicked page routing', async () => { + const browser = await webdriver(next.url, '/root') + try { + await browser.elementById('go-to-hello-world-anchor').click() + const routeName = await browser.elementById('route-name').text() + expect(routeName).toMatch('hello-world') + } finally { + await browser.close() + } + }) })