mirror of
https://github.com/hanzoai/next.js.git
synced 2026-10-30 14:46:38 +00:00
## 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 ``` ---------
42 lines
1.1 KiB
JavaScript
42 lines
1.1 KiB
JavaScript
import Link from 'next/link'
|
|
import './global.css'
|
|
|
|
export default function HashPage() {
|
|
// Create list of 5000 items that all have unique id
|
|
const items = Array.from({ length: 5000 }, (_, i) => ({ id: i }))
|
|
|
|
return (
|
|
<div style={{ fontFamily: 'sans-serif', fontSize: '16px' }}>
|
|
<p>Hash Page</p>
|
|
<Link href="/hash#hash-6" id="link-to-6">
|
|
To 6
|
|
</Link>
|
|
<Link href="/hash#hash-50" id="link-to-50">
|
|
To 50
|
|
</Link>
|
|
<Link href="/hash#hash-160" id="link-to-160">
|
|
To 160
|
|
</Link>
|
|
<Link href="/hash#hash-300" id="link-to-300">
|
|
To 300
|
|
</Link>
|
|
<Link href="#hash-500" id="link-to-500">
|
|
To 500 (hash only)
|
|
</Link>
|
|
<Link href="/hash#top" id="link-to-top">
|
|
To Top
|
|
</Link>
|
|
<Link href="/hash#non-existent" id="link-to-non-existent">
|
|
To non-existent
|
|
</Link>
|
|
<div>
|
|
{items.map((item) => (
|
|
<div key={item.id}>
|
|
<div id={`hash-${item.id}`}>{item.id}</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|