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}
+