Unverified Commit 1df2686b authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Remove Base Path from usePathname output (#53582)

This removes the `basePath` from the output of `usePathname`. Previously this always resulted in hydration errors, this now strips the `basePath` when it's found/configured.

Now when you configure `basePath`, you don't have to factor it into your application logic and can instead rely on the values always returning the pathname without it.

Fixes #46562 
parent 1d8a6335
......@@ -57,6 +57,8 @@ import { RedirectBoundary } from './redirect-boundary'
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'
import { createInfinitePromise } from './infinite-promise'
import { NEXT_RSC_UNION_QUERY } from './app-router-headers'
import { removeBasePath } from '../remove-base-path'
import { hasBasePath } from '../has-base-path'
const isServer = typeof window === 'undefined'
......@@ -251,7 +253,9 @@ function Router({
return {
// This is turned into a readonly class in `useSearchParams`
searchParams: url.searchParams,
pathname: url.pathname,
pathname: hasBasePath(url.pathname)
? removeBasePath(url.pathname)
: url.pathname,
}
}, [canonicalUrl])
......
......@@ -9,6 +9,9 @@ export function removeBasePath(path: string): string {
}
}
// Can't trim the basePath if it has zero length!
if (basePath.length === 0) return path
path = path.slice(basePath.length)
if (!path.startsWith('/')) path = `/${path}`
return path
......
'use client'
export { Page as default } from '../../components/page'
export default function Layout({ children }) {
return (
<html>
<head />
<body>{children}</body>
</html>
)
}
'use client'
export { Page as default } from '../components/page'
import { usePathname } from 'next/navigation'
export function Page() {
const pathname = usePathname()
return (
<div id="pathname" data-pathname={pathname}>
{pathname}
</div>
)
}
import { createNextDescribe } from 'e2e-utils'
import { basePath } from './next.config'
createNextDescribe(
'base path support for usePathname',
{
files: __dirname,
},
({ next }) => {
it.each(['/', '/dashboard'])(
'should render %s without the basePath',
async (pathname) => {
const $ = await next.render$(basePath + pathname)
expect($('#pathname').data('pathname')).toBe(pathname)
}
)
}
)
module.exports = {
basePath: '/docs',
}
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