Unverified Commit ef2b8f86 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix canonical url for dynamic routes (#49512)

The `pathname` in app-render was actually "page" (e.g. `/blog/[slug]`),
with special url conventions. Instead we should use actual request url
as pathname. Rename previous `pathname` arg to `pagePath` for better
readability

Also improved the url validation
parent 064e0c25
......@@ -138,11 +138,12 @@ function findDynamicParamFromRouterState(
export async function renderToHTMLOrFlight(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
pagePath: string,
query: NextParsedUrlQuery,
renderOpts: RenderOpts
): Promise<RenderResult> {
const isFlight = req.headers[RSC.toLowerCase()] !== undefined
const pathname = validateURL(req.url)
const {
buildManifest,
......@@ -699,7 +700,7 @@ export async function renderToHTMLOrFlight(
!isValidElementType(Component)
) {
throw new Error(
`The default export is not a React Component in page: "${pathname}"`
`The default export is not a React Component in page: "${page}"`
)
}
......@@ -1179,7 +1180,7 @@ export async function renderToHTMLOrFlight(
injectedCSS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
asNotFound: pathname === '/404' || options?.asNotFound,
asNotFound: pagePath === '/404' || options?.asNotFound,
})
).map((path) => path.slice(1)) // remove the '' (root) segment
......@@ -1216,8 +1217,6 @@ export async function renderToHTMLOrFlight(
Uint8Array
> = new TransformStream()
const initialCanonicalUrl = validateURL(req.url)
// Get the nonce from the incoming request if it has one.
const csp = req.headers['content-security-policy']
let nonce: string | undefined
......@@ -1297,7 +1296,7 @@ export async function renderToHTMLOrFlight(
{styles}
<AppRouter
assetPrefix={assetPrefix}
initialCanonicalUrl={initialCanonicalUrl}
initialCanonicalUrl={pathname}
initialTree={initialTree}
initialHead={
<>
......@@ -1361,13 +1360,13 @@ export async function renderToHTMLOrFlight(
)
}
getTracer().getRootSpanAttributes()?.set('next.route', pathname)
getTracer().getRootSpanAttributes()?.set('next.route', pagePath)
const bodyResult = getTracer().wrap(
AppRenderSpan.getBodyResult,
{
spanName: `render route (app) ${pathname}`,
spanName: `render route (app) ${pagePath}`,
attributes: {
'next.route': pathname,
'next.route': pagePath,
},
},
async ({
......@@ -1497,8 +1496,8 @@ export async function renderToHTMLOrFlight(
}
if (err.digest === NEXT_DYNAMIC_NO_SSR_CODE) {
warn(
`Entire page ${pathname} deopted into client-side rendering. https://nextjs.org/docs/messages/deopted-into-client-rendering`,
pathname
`Entire page ${pagePath} deopted into client-side rendering. https://nextjs.org/docs/messages/deopted-into-client-rendering`,
pagePath
)
}
if (isNotFoundError(err)) {
......@@ -1571,7 +1570,7 @@ export async function renderToHTMLOrFlight(
const renderResult = new RenderResult(
await bodyResult({
asNotFound: pathname === '/404',
asNotFound: pagePath === '/404',
})
)
......@@ -1625,7 +1624,7 @@ export async function renderToHTMLOrFlight(
() =>
StaticGenerationAsyncStorageWrapper.wrap(
staticGenerationAsyncStorage,
{ pathname, renderOpts },
{ pathname: pagePath, renderOpts },
() => wrappedRender()
)
)
......
const DUMMY_ORIGIN = 'http://n'
const INVALID_URL_MESSAGE = 'Invalid request URL'
export function validateURL(url: string | undefined): string {
if (!url) {
throw new Error('Invalid request URL')
throw new Error(INVALID_URL_MESSAGE)
}
try {
new URL(url, 'http://n')
const parsed = new URL(url, DUMMY_ORIGIN)
// Avoid origin change by extra slashes in pathname
if (parsed.origin !== DUMMY_ORIGIN) {
throw new Error(INVALID_URL_MESSAGE)
}
return url
} catch {
throw new Error('Invalid request URL')
throw new Error(INVALID_URL_MESSAGE)
}
}
export default function Page() {
return 'alternate-child-dynamic-slug'
}
......@@ -337,6 +337,11 @@ createNextDescribe(
rel: 'alternate',
href: 'https://example.com/alternates/child/de-DE',
})
await browser.loadPage(next.url + '/alternates/child/123')
await matchDom('link', 'rel="canonical"', {
href: 'https://example.com/alternates/child/123',
})
})
it('should support robots tags', async () => {
......
import { validateURL } from 'next/dist/server/app-render/validate-url'
describe('validateUrl', () => {
it('should return valid pathname', () => {
expect(validateURL('/')).toBe('/')
expect(validateURL('/abc')).toBe('/abc')
})
it('should throw for invalid pathname', () => {
expect(() => validateURL('//**y/\\')).toThrow()
expect(() => validateURL('//google.com')).toThrow()
})
})
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