Files
Jiwon ChoiandGitHub ff4f10a510 [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
2025-08-05 20:15:16 +02:00

34 lines
868 B
JavaScript

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
rewrites: async () => {
return {
beforeFiles: [
{
source: '/',
destination: '/foo',
},
{
source: '/rewrite-to-another-segment/:id',
destination: '/rewrite-to-another-segment/:id/foo',
},
// Even though there's rewrite, below won't work as expected due to trade-off.
{
source: '/rewrite-to-same-segment/1',
destination: '/rewrite-to-same-segment/001',
},
{
source: '/rewrite-to-same-segment/2',
destination: '/rewrite-to-same-segment/002',
},
{
source: '/rewrite-to-same-segment/3',
destination: '/rewrite-to-same-segment/003',
},
],
}
},
}
module.exports = nextConfig