Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide metadataBase with request info by default #46156

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions packages/next/src/lib/metadata/metadata.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,14 @@ import { IconsMetadata } from './generate/icons'
import { accumulateMetadata, MetadataItems } from './resolve-metadata'

// Generate the actual React elements from the resolved metadata.
export async function MetadataTree({ metadata }: { metadata: MetadataItems }) {
const resolved = await accumulateMetadata(metadata)
export async function MetadataTree({
metadata,
urlBase,
}: {
metadata: MetadataItems
urlBase: string
}) {
const resolved = await accumulateMetadata(metadata, urlBase)

return (
<>
Expand Down
6 changes: 3 additions & 3 deletions packages/next/src/lib/metadata/resolve-metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe('accumulateMetadata', () => {
[() => Promise.resolve({ description: 'child' }), null],
]

const metadata = await accumulateMetadata(metadataItems)
const metadata = await accumulateMetadata(metadataItems, undefined)
expect(metadata).toMatchObject({
description: 'child',
})
Expand All @@ -23,7 +23,7 @@ describe('accumulateMetadata', () => {
[{ title: 'layout' }, null],
[{ title: 'page' }, null],
]
const metadata = await accumulateMetadata(metadataItems)
const metadata = await accumulateMetadata(metadataItems, undefined)
expect(metadata).toMatchObject({
title: { absolute: 'page', template: null },
})
Expand All @@ -43,7 +43,7 @@ describe('accumulateMetadata', () => {
[null, null], // same level layout
[{ title: 'page' }, null],
]
const metadata = await accumulateMetadata(metadataItems)
const metadata = await accumulateMetadata(metadataItems, undefined)
expect(metadata).toMatchObject({
title: { absolute: '2nd parent layout page', template: null },
})
Expand Down
25 changes: 20 additions & 5 deletions packages/next/src/lib/metadata/resolve-metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ function mergeStaticMetadata(
card: 'summary_large_image',
images: twitter,
},
null
metadata.metadataBase
)
metadata.twitter = { ...metadata.twitter, ...resolvedTwitter! }
}
Expand All @@ -62,7 +62,7 @@ function mergeStaticMetadata(
{
images: opengraph,
},
null
metadata.metadataBase
)
metadata.openGraph = { ...metadata.openGraph, ...resolvedOg! }
}
Expand All @@ -81,7 +81,8 @@ function merge(
openGraph: string | null
}
) {
const metadataBase = source?.metadataBase || null
const metadataBase = source?.metadataBase || target.metadataBase

for (const key_ in source) {
const key = key_ as keyof Metadata

Expand Down Expand Up @@ -166,7 +167,7 @@ function merge(
target.other = Object.assign({}, target.other, source.other)
break
case 'metadataBase':
target.metadataBase = metadataBase
if (metadataBase) target.metadataBase = metadataBase
break
default:
break
Expand Down Expand Up @@ -239,8 +240,18 @@ export async function collectMetadata(
array.push([metadataExport, staticFilesMetadata])
}

function constructMetadataBase(urlBase: string) {
// Use the host of request for metadataBase
try {
return new URL(urlBase)
} catch (_) {
return null
}
}

export async function accumulateMetadata(
metadataItems: MetadataItems
metadataItems: MetadataItems,
urlBase: string | undefined
): Promise<ResolvedMetadata> {
const resolvedMetadata = createDefaultMetadata()

Expand All @@ -260,6 +271,10 @@ export async function accumulateMetadata(
// Loop over all metadata items again, merging synchronously any static object exports,
// awaiting any static promise exports, and resolving parent metadata and awaiting any generated metadata

if (urlBase) {
resolvedMetadata.metadataBase = constructMetadataBase(urlBase)
}

let resolvingIndex = 0
for (let i = 0; i < metadataItems.length; i++) {
const [metadataExport, staticFilesMetadata] = metadataItems[i]
Expand Down
11 changes: 10 additions & 1 deletion packages/next/src/lib/metadata/resolvers/resolve-opengraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,16 @@ export function resolveOpenGraph(
}
}
}
resolved.images = resolveAsArrayOrUndefined(og.images)
resolved.images = resolveAsArrayOrUndefined(og.images)?.map((item) => {
if (isStringOrURL(item))
return {
url: resolveUrl(item, metadataBase)!,
}
else {
item.url = resolveUrl(item.url, metadataBase)!
return item
}
})
}

assignProps(openGraph)
Expand Down
18 changes: 15 additions & 3 deletions packages/next/src/server/app-render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,10 @@ export async function renderToHTMLOrFlight(
typeof actionId === 'string' &&
req.method === 'POST'

const protocol = req.headers['x-forwarded-proto'] || 'http'
const host = req.headers.host
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is potentially dangerous when this incoming request header is trusted in an environment where it is passed through directly. Can you have a look at how this is handled for edge where a full URL is required as well and mirror that approach?

const urlBase = `${protocol}://${host}`

const {
buildManifest,
subresourceIntegrityManifest,
Expand Down Expand Up @@ -1813,7 +1817,11 @@ export async function renderToHTMLOrFlight(
<>
{/* Adding key={requestId} to make metadata remount for each render */}
{/* @ts-expect-error allow to use async server component */}
<MetadataTree key={requestId} metadata={metadataItems} />
<MetadataTree
key={requestId}
metadata={metadataItems}
urlBase={urlBase}
/>
{resolvedHead}
</>
),
Expand Down Expand Up @@ -1928,9 +1936,13 @@ export async function renderToHTMLOrFlight(
initialTree={initialTree}
initialHead={
<>
{/* Adding key={requestId} to make metadata remount for each render */}
{/* @ts-expect-error allow to use async server component */}
<MetadataTree key={requestId} metadata={metadataItems} />
<MetadataTree
// Adding key={requestId} to make metadata remount for each render
key={requestId}
urlBase={urlBase}
metadata={metadataItems}
/>
{initialHead}
</>
}
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/app-dir/metadata/metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ createNextDescribe(
it('should pick up opengraph-image and twitter-image as static metadata files', async () => {
const $ = await next.render$('/opengraph/static')
expect($('[property="og:image:url"]').attr('content')).toMatch(
/_next\/static\/media\/metadata\/opengraph-image.\w+.png/
/http:\/\/\w+:\w+\/_next\/static\/media\/metadata\/opengraph-image.\w+.png/
)
expect($('[property="og:image:type"]').attr('content')).toBe(
'image/png'
Expand All @@ -459,7 +459,7 @@ createNextDescribe(
expect($('[property="og:image:height"]').attr('content')).toBe('114')

expect($('[name="twitter:image"]').attr('content')).toMatch(
/_next\/static\/media\/metadata\/twitter-image.\w+.png/
/http:\/\/\w+:\w+\/_next\/static\/media\/metadata\/twitter-image.\w+.png/
)
expect($('[name="twitter:card"]').attr('content')).toBe(
'summary_large_image'
Expand Down