Unverified Commit 5a7cec1e authored by BYUNGI's avatar BYUNGI Committed by GitHub

fix(router): Prevent redirect loop on root data requests with basePath (#81096)

Fixes #64910

This PR resolves an issue where a client-side navigation to the root
page fails when both `basePath` and `middleware` are active. This is
caused by an incorrect redirect loop on the `/_next/data` request.

The sequence of events is as follows:
1. Next.js enforces its `trailingSlash: false` policy by adding an
internal redirect from `{basePath}/` to `{basePath}`.
2. For middleware to be invoked correctly, a data request for the root
page is normalized to `/`.
3. The path is then re-joined with the `basePath` using
`path.posix.join(config.basePath, '/')`, which incorrectly results in
`{basePath}/`.
4. This malformed path triggers the redirect from step 1, causing the
data fetch to fail with a 308 status code and resulting in empty
`pageProps`.

This fix isolates the root path (`/`) during path normalization to
prevent an extra trailing slash from being added. By ensuring the path
resolves to `{basePath}` instead of `{basePath}/`, the redirect loop is
avoided.

The change correctly handles the root path while leaving the logic for
all other paths untouched.

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 16011fe8
......@@ -423,7 +423,10 @@ export function getResolveRoutes(
// base path.
if (updated) {
if (hadBasePath) {
normalized = path.posix.join(config.basePath, normalized)
normalized =
normalized === '/'
? config.basePath
: path.posix.join(config.basePath, normalized)
}
// Re-add the trailing slash (if required).
......
import Link from 'next/link'
export default function Other() {
return (
<div>
<h1>Other page</h1>
<Link href="/" id="go-to-home">
Go to home
</Link>
</div>
)
}
......@@ -35,6 +35,7 @@ describe('Middleware base tests', () => {
const $ = cheerio.load(html)
expect($('.title').text()).toBe('About Page')
})
it('router.query must exist when Link clicked page routing', async () => {
const browser = await webdriver(next.url, '/root')
try {
......@@ -45,4 +46,15 @@ describe('Middleware base tests', () => {
await browser.close()
}
})
it('should allow client-side navigation to the root', async () => {
const browser = await webdriver(next.url, '/root/other')
try {
await browser.elementById('go-to-home').click()
const title = await browser.waitForElementByCss('.title').text()
expect(title).toMatch('Hello World')
} finally {
await browser.close()
}
})
})
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