Unverified Commit ff4f10a5 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

[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
parent ffd7f13c
......@@ -8,6 +8,8 @@ import { normalizePathTrailingSlash } from './normalize-trailing-slash'
import { isLocalURL } from '../shared/lib/router/utils/is-local-url'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { interpolateAs } from '../shared/lib/router/utils/interpolate-as'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
/**
* Resolves a given hyperlink with a certain router state (basePath not included).
......@@ -56,10 +58,39 @@ export function resolveHref(
}
try {
base = new URL(
urlAsString.startsWith('#') ? router.asPath : router.pathname,
'http://n'
)
let baseBase = urlAsString.startsWith('#') ? router.asPath : router.pathname
// If the provided href is only a query string, it is safer to use the asPath
// considering rewrites.
if (urlAsString.startsWith('?')) {
baseBase = router.asPath
// However, if is a dynamic route, we need to use the pathname to preserve the
// query interpolation and rewrites (router.pathname will look like "/[slug]").
if (isDynamicRoute(router.pathname)) {
baseBase = router.pathname
const routeRegex = getRouteRegex(router.pathname)
const match = getRouteMatcher(routeRegex)(router.asPath)
// For dynamic routes, if asPath doesn't match the pathname regex, it is a rewritten path.
// In this case, should use asPath to preserve the current URL.
if (!match) {
baseBase = 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.
}
}
base = new URL(baseBase, 'http://n')
} catch (_) {
// fallback to / for invalid asPath values e.g. //
base = new URL('/', 'http://n')
......
/** @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
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
function handlePush() {
router.push({
query: {
param: 1,
},
})
}
function handleReplace() {
router.replace({
query: {
param: 1,
},
})
}
return (
<>
<button id="router-push" onClick={handlePush}>
router.push
</button>
<button id="router-replace" onClick={handleReplace}>
router.replace
</button>
<Link href="?param=1">Link</Link>
</>
)
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
function handlePush() {
router.push({
query: {
id: 1,
},
})
}
function handleReplace() {
router.replace({
query: {
id: 2,
},
})
}
return (
<>
<p>{router.query.id}</p>
<button id="router-push" onClick={handlePush}>
router.push
</button>
<button id="router-replace" onClick={handleReplace}>
router.replace
</button>
<Link href="?id=3">Link</Link>
</>
)
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
function handlePush() {
router.push({
query: {
id: 1,
},
})
}
function handleReplace() {
router.replace({
query: {
id: 2,
},
})
}
return (
<>
<p>{router.query.id}</p>
<button id="router-push" onClick={handlePush}>
router.push
</button>
<button id="router-replace" onClick={handleReplace}>
router.replace
</button>
<Link href="?id=3">Link</Link>
</>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('use-router-with-rewrites', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should preserve current pathname when using useRouter.push with rewrites', async () => {
const browser = await next.browser('/')
await browser.elementById('router-push').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/?param=1')
})
it('should preserve current pathname when using useRouter.replace with rewrites', async () => {
const browser = await next.browser('/')
await browser.elementById('router-replace').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/?param=1')
})
it('should preserve current pathname when using Link with rewrites', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/?param=1')
})
describe('rewrite to another segment', () => {
it('should preserve current pathname when using useRouter.push with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-another-segment/0')
await browser.elementById('router-push').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe(
'/rewrite-to-another-segment/0?id=1'
)
})
it('should preserve current pathname when using useRouter.replace with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-another-segment/0')
await browser.elementById('router-replace').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe(
'/rewrite-to-another-segment/0?id=2'
)
})
it('should preserve current pathname when using Link with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-another-segment/0')
await browser.elementByCss('a').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe(
'/rewrite-to-another-segment/0?id=3'
)
})
})
// This is an edge case where rewrite won't work as expected due to trade-off,
// but interpolates the query instead.
describe('rewrite to same segment', () => {
it('should preserve current pathname when using useRouter.push with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementById('router-push').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/1')
expect(await browser.elementByCss('p').text()).toBe('1')
})
it('should preserve current pathname when using useRouter.replace with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementById('router-replace').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/2')
expect(await browser.elementByCss('p').text()).toBe('2')
})
it('should preserve current pathname when using Link with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementByCss('a').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/3')
expect(await browser.elementByCss('p').text()).toBe('3')
})
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment