next.js
ff4f10a5 - [Pages] fix: use `asPath` for query-only navigation with `useRouter` (#82236)

Commit
230 days ago
[Pages] fix: use `asPath` for query-only navigation with `useRouter` (#82236) ### Why? The issue was brought up when the app had rewrites (say `/ -> /foo`), and the page used `useRouter.push/replace` to add the search queries; it used the destination's pathname (`/foo?query=1`) instead of just adding the query (`/?query=1`). Current Behavior: https://github.com/vercel/next.js/actions/runs/16647831682/job/47112716254?pr=82236#step:34:156 ### How? Therefore, as we handle the hash (`#`), if the target path only needs a query `?`, we may use `router.asPath` by default for static routes to resolve cases with rewrites. However, if it is a dynamic route, it needs to be able to interpolate the query (for `/[id]` segment, `/?id=1` interpolates to `/1` route), so use `router.pathname`. Finally, if it is suspected to be a rewritten path, use `router.asPath`. **Note:** There is an edge case where the pathname is dynamic, and also a rewrite path to the same segment. E.g. in `/[slug]` path, rewrite `/foo -> /bar` In this case, it will be treated as a non-rewritten path and possibly interpolate the query string. E.g., `/any?slug=foo` will become the content of `/foo`, not rewritten as `/bar`. This is currently a trade-off of not resolving rewrite paths on every Router/Link call, but using a lighter route regex pattern check. Fixes https://github.com/vercel/next.js/issues/81476
Author
Parents
Loading