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( ...@@ -138,11 +138,12 @@ function findDynamicParamFromRouterState(
export async function renderToHTMLOrFlight( export async function renderToHTMLOrFlight(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
pathname: string, pagePath: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: RenderOpts renderOpts: RenderOpts
): Promise<RenderResult> { ): Promise<RenderResult> {
const isFlight = req.headers[RSC.toLowerCase()] !== undefined const isFlight = req.headers[RSC.toLowerCase()] !== undefined
const pathname = validateURL(req.url)
const { const {
buildManifest, buildManifest,
...@@ -699,7 +700,7 @@ export async function renderToHTMLOrFlight( ...@@ -699,7 +700,7 @@ export async function renderToHTMLOrFlight(
!isValidElementType(Component) !isValidElementType(Component)
) { ) {
throw new Error( 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( ...@@ -1179,7 +1180,7 @@ export async function renderToHTMLOrFlight(
injectedCSS: new Set(), injectedCSS: new Set(),
injectedFontPreloadTags: new Set(), injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false, rootLayoutIncluded: false,
asNotFound: pathname === '/404' || options?.asNotFound, asNotFound: pagePath === '/404' || options?.asNotFound,
}) })
).map((path) => path.slice(1)) // remove the '' (root) segment ).map((path) => path.slice(1)) // remove the '' (root) segment
...@@ -1216,8 +1217,6 @@ export async function renderToHTMLOrFlight( ...@@ -1216,8 +1217,6 @@ export async function renderToHTMLOrFlight(
Uint8Array Uint8Array
> = new TransformStream() > = new TransformStream()
const initialCanonicalUrl = validateURL(req.url)
// Get the nonce from the incoming request if it has one. // Get the nonce from the incoming request if it has one.
const csp = req.headers['content-security-policy'] const csp = req.headers['content-security-policy']
let nonce: string | undefined let nonce: string | undefined
...@@ -1297,7 +1296,7 @@ export async function renderToHTMLOrFlight( ...@@ -1297,7 +1296,7 @@ export async function renderToHTMLOrFlight(
{styles} {styles}
<AppRouter <AppRouter
assetPrefix={assetPrefix} assetPrefix={assetPrefix}
initialCanonicalUrl={initialCanonicalUrl} initialCanonicalUrl={pathname}
initialTree={initialTree} initialTree={initialTree}
initialHead={ initialHead={
<> <>
...@@ -1361,13 +1360,13 @@ export async function renderToHTMLOrFlight( ...@@ -1361,13 +1360,13 @@ export async function renderToHTMLOrFlight(
) )
} }
getTracer().getRootSpanAttributes()?.set('next.route', pathname) getTracer().getRootSpanAttributes()?.set('next.route', pagePath)
const bodyResult = getTracer().wrap( const bodyResult = getTracer().wrap(
AppRenderSpan.getBodyResult, AppRenderSpan.getBodyResult,
{ {
spanName: `render route (app) ${pathname}`, spanName: `render route (app) ${pagePath}`,
attributes: { attributes: {
'next.route': pathname, 'next.route': pagePath,
}, },
}, },
async ({ async ({
...@@ -1497,8 +1496,8 @@ export async function renderToHTMLOrFlight( ...@@ -1497,8 +1496,8 @@ export async function renderToHTMLOrFlight(
} }
if (err.digest === NEXT_DYNAMIC_NO_SSR_CODE) { if (err.digest === NEXT_DYNAMIC_NO_SSR_CODE) {
warn( warn(
`Entire page ${pathname} deopted into client-side rendering. https://nextjs.org/docs/messages/deopted-into-client-rendering`, `Entire page ${pagePath} deopted into client-side rendering. https://nextjs.org/docs/messages/deopted-into-client-rendering`,
pathname pagePath
) )
} }
if (isNotFoundError(err)) { if (isNotFoundError(err)) {
...@@ -1571,7 +1570,7 @@ export async function renderToHTMLOrFlight( ...@@ -1571,7 +1570,7 @@ export async function renderToHTMLOrFlight(
const renderResult = new RenderResult( const renderResult = new RenderResult(
await bodyResult({ await bodyResult({
asNotFound: pathname === '/404', asNotFound: pagePath === '/404',
}) })
) )
...@@ -1625,7 +1624,7 @@ export async function renderToHTMLOrFlight( ...@@ -1625,7 +1624,7 @@ export async function renderToHTMLOrFlight(
() => () =>
StaticGenerationAsyncStorageWrapper.wrap( StaticGenerationAsyncStorageWrapper.wrap(
staticGenerationAsyncStorage, staticGenerationAsyncStorage,
{ pathname, renderOpts }, { pathname: pagePath, renderOpts },
() => wrappedRender() () => wrappedRender()
) )
) )
......
const DUMMY_ORIGIN = 'http://n'
const INVALID_URL_MESSAGE = 'Invalid request URL'
export function validateURL(url: string | undefined): string { export function validateURL(url: string | undefined): string {
if (!url) { if (!url) {
throw new Error('Invalid request URL') throw new Error(INVALID_URL_MESSAGE)
} }
try { 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 return url
} catch { } 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( ...@@ -337,6 +337,11 @@ createNextDescribe(
rel: 'alternate', rel: 'alternate',
href: 'https://example.com/alternates/child/de-DE', 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 () => { 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