Unverified Commit 8e202610 authored by Keyan Zhang's avatar Keyan Zhang Committed by GitHub

App Router: fix relative query/hash handling in `next/link` and router push/replace (#49521)

## Problem
Relative hash/query handling in `next/link` (e.g. `<Link
href="#hello">`) is broken in App Router, especially if you're on a
nested route.

This wasn't a problem in `/pages` because the href always get fully
resolved in `<NextLink>`; i.e. if you have `<Link href="#hash" />` on
`/hello`, it'll resolve the href to `/hello#hash` and use that
everywhere.

However, in App Router, `<Link>` no longer uses the current location to
resolve the href:
https://github.com/vercel/next.js/blob/5451564f364399003b05939fa6dd7d32c1dabec7/packages/next/src/client/link.tsx#L450-L457

Therefore navigating with `new URL(href, location.origin)` will skip the
current path and always apply the relative hash/query to the _root_
route:
https://github.com/vercel/next.js/blob/5451564f364399003b05939fa6dd7d32c1dabec7/packages/next/src/client/components/app-router.tsx#L208-L215

## Solution
Not 100% sure if this is the best solution, but since `app-router` is
already reading `window.location`, I'm using `location.href` as the base
URL to resolve the href.

I grep'd for `location.origin` and checked other callsites; seems like
only `app-router` deals with user specified hrefs.

Fixes https://github.com/vercel/next.js/issues/42157 &
https://github.com/vercel/next.js/issues/44139, and potentially
https://github.com/vercel/next.js/issues/48554 and
https://github.com/vercel/next.js/issues/22838

## Test Plan
```
pnpm testheadless test/e2e/app-dir/navigation
```

---------
parent 3f164abd
...@@ -211,7 +211,7 @@ function Router({ ...@@ -211,7 +211,7 @@ function Router({
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean forceOptimisticNavigation: boolean
) => { ) => {
const url = new URL(addBasePath(href), location.origin) const url = new URL(addBasePath(href), location.href)
return dispatch({ return dispatch({
type: ACTION_NAVIGATE, type: ACTION_NAVIGATE,
...@@ -261,7 +261,7 @@ function Router({ ...@@ -261,7 +261,7 @@ function Router({
if (isBot(window.navigator.userAgent)) { if (isBot(window.navigator.userAgent)) {
return return
} }
const url = new URL(addBasePath(href), location.origin) const url = new URL(addBasePath(href), location.href)
// External urls can't be prefetched in the same way. // External urls can't be prefetched in the same way.
if (isExternalURL(url)) { if (isExternalURL(url)) {
return return
......
...@@ -20,6 +20,9 @@ export default function HashPage() { ...@@ -20,6 +20,9 @@ export default function HashPage() {
<Link href="/hash#hash-300" id="link-to-300"> <Link href="/hash#hash-300" id="link-to-300">
To 300 To 300
</Link> </Link>
<Link href="#hash-500" id="link-to-500">
To 500 (hash only)
</Link>
<Link href="/hash#top" id="link-to-top"> <Link href="/hash#top" id="link-to-top">
To Top To Top
</Link> </Link>
......
'use client'
import { useRouter } from 'next/navigation'
export function RouterPushButton() {
const router = useRouter()
return (
<h3 id="h3">
<button
id="button-to-h3-hash-only"
onClick={() => {
router.push('#h3')
}}
>
To #h3, hash only
</button>
</h3>
)
}
import Link from 'next/link'
import { RouterPushButton } from './client-component'
export default function Page() {
return (
<>
<h1 id="h1">
<Link href="#h1" id="link-to-h1-hash-only">
To #h1, hash only
</Link>
</h1>
<p>
<Link href="?foo=1&bar=2" id="link-to-dummy-query">
Query only
</Link>
</p>
<h2 id="h2">
<Link href="?here=ok#h2" id="link-to-h2-with-hash-and-query">
To #h2, with both relative hash and query
</Link>
</h2>
<RouterPushButton />
</>
)
}
...@@ -52,6 +52,7 @@ createNextDescribe( ...@@ -52,6 +52,7 @@ createNextDescribe(
await checkLink(50, 730) await checkLink(50, 730)
await checkLink(160, 2270) await checkLink(160, 2270)
await checkLink(300, 4230) await checkLink(300, 4230)
await checkLink(500, 7030) // this one is hash only (`href="#hash-500"`)
await checkLink('top', 0) await checkLink('top', 0)
await checkLink('non-existent', 0) await checkLink('non-existent', 0)
}) })
...@@ -106,6 +107,60 @@ createNextDescribe( ...@@ -106,6 +107,60 @@ createNextDescribe(
}) })
}) })
describe('relative hashes and queries', () => {
const pathname = '/nested-relative-query-and-hash'
it('should work with a hash-only href', async () => {
const browser = await next.browser(pathname)
await browser.elementByCss('#link-to-h1-hash-only').click()
await check(() => browser.url(), next.url + pathname + '#h1')
})
it('should work with a hash-only `router.push(...)`', async () => {
const browser = await next.browser(pathname)
await browser.elementByCss('#button-to-h3-hash-only').click()
await check(() => browser.url(), next.url + pathname + '#h3')
})
it('should work with a query-only href', async () => {
const browser = await next.browser(pathname)
await browser.elementByCss('#link-to-dummy-query').click()
await check(() => browser.url(), next.url + pathname + '?foo=1&bar=2')
})
it('should work with both relative hashes and queries', async () => {
const browser = await next.browser(pathname)
await browser.elementByCss('#link-to-h2-with-hash-and-query').click()
await check(() => browser.url(), next.url + pathname + '?here=ok#h2')
// Only update hash
await browser.elementByCss('#link-to-h1-hash-only').click()
await check(() => browser.url(), next.url + pathname + '?here=ok#h1')
// Replace all with new query
await browser.elementByCss('#link-to-dummy-query').click()
await check(() => browser.url(), next.url + pathname + '?foo=1&bar=2')
// Add hash to existing query
await browser.elementByCss('#link-to-h1-hash-only').click()
await check(
() => browser.url(),
next.url + pathname + '?foo=1&bar=2#h1'
)
// Update hash again via `router.push(...)`
await browser.elementByCss('#button-to-h3-hash-only').click()
await check(
() => browser.url(),
next.url + pathname + '?foo=1&bar=2#h3'
)
})
})
describe('not-found', () => { describe('not-found', () => {
it('should trigger not-found in a server component', async () => { it('should trigger not-found in a server component', async () => {
const browser = await next.browser('/not-found/servercomponent') const browser = await next.browser('/not-found/servercomponent')
......
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