Unverified Commit 68f328f9 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix: fill route params for dynamic route metadata images url (#47829)

Should fill dynamic routes url with params when generate the metadata
image urls.

For `/(group)`, we need to normalize the path first;
For dynamic routes `/[slug]`, we need to fill the params.

Change the image module from `() => image` to `(prop) => image(proop)`
so we can fill the runtime `params` into url

Closes NEXT-932

---------
parent de97a94d
......@@ -103,9 +103,9 @@ export async function createStaticMetadataFromRoute(
}
)}!${filepath}${METADATA_RESOURCE_QUERY}`
const imageModule = `() => import(/* webpackMode: "eager" */ ${JSON.stringify(
const imageModule = `(async (props) => (await import(/* webpackMode: "eager" */ ${JSON.stringify(
imageModuleImportSource
)})`
)})).default(props))`
hasStaticMetadataFiles = true
if (type === 'favicon') {
staticImagesMetadata.icon.unshift(imageModule)
......
......@@ -20,6 +20,7 @@ import { isAppRouteRoute } from '../../../lib/is-app-route-route'
import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route'
import { NextConfig } from '../../../server/config-shared'
import { AppPathnameNormalizer } from '../../../server/future/normalizers/built/app/app-pathname-normalizer'
import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths'
export type AppLoaderOptions = {
name: string
......@@ -254,7 +255,7 @@ async function createTreeCodeFromPath(
if (resolvedRouteDir) {
metadata = await createStaticMetadataFromRoute(resolvedRouteDir, {
route: segmentPath,
route: normalizeAppPath(segmentPath),
resolvePath,
isRootLayer,
loaderContext,
......
......@@ -22,7 +22,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
const { type, route, pageExtensions } = options
const numericSizes = type === 'twitter' || type === 'openGraph'
const { resourcePath, rootContext: context } = this
const { name: filename, ext } = path.parse(resourcePath)
const { name: fileNameBase, ext } = path.parse(resourcePath)
let extension = ext.slice(1)
if (extension === 'jpg') {
......@@ -31,42 +31,52 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
const opts = { context, content }
const interpolatedName = loaderUtils.interpolateName(
this,
'[name].[ext]',
opts
)
// No hash query for favicon.ico
const contentHash =
type === 'favicon'
? ''
: loaderUtils.interpolateName(this, '[contenthash]', opts)
const outputPath =
route + '/' + interpolatedName + (contentHash ? `?${contentHash}` : '')
const interpolatedName = loaderUtils.interpolateName(
this,
'[name].[ext]',
opts
)
const isDynamicResource = pageExtensions.includes(extension)
const pageRoute =
(isDynamicResource ? fileNameBase : interpolatedName) +
(contentHash ? '?' + contentHash : '')
if (isDynamicResource) {
// re-export and spread as `exportedImageData` to avoid non-exported error
return `\
import path from 'path'
import * as exported from ${JSON.stringify(resourcePath)}
import { interpolateDynamicPath } from 'next/dist/server/server-utils'
import { getNamedRouteRegex } from 'next/dist/shared/lib/router/utils/route-regex'
const exportedImageData = { ...exported }
const imageData = {
alt: exportedImageData.alt,
type: exportedImageData.contentType,
url: ${JSON.stringify(route + '/' + filename + '?' + contentHash)},
}
const { size } = exportedImageData
if (size) {
${
type === 'twitter' || type === 'openGraph'
? 'imageData.width = size.width; imageData.height = size.height;'
: 'imageData.sizes = size.width + "x" + size.height;'
export default (props) => {
const pathname = ${JSON.stringify(route)}
const routeRegex = getNamedRouteRegex(pathname)
const route = interpolateDynamicPath(pathname, props.params, routeRegex)
const imageData = {
alt: exportedImageData.alt,
type: exportedImageData.contentType,
url: path.join(route, ${JSON.stringify(pageRoute)}),
}
}
export default imageData`
const { size } = exportedImageData
if (size) {
${
type === 'twitter' || type === 'openGraph'
? 'imageData.width = size.width; imageData.height = size.height;'
: 'imageData.sizes = size.width + "x" + size.height;'
}
}
return imageData
}`
}
const imageSize = await getImageSize(
......@@ -80,8 +90,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
throw err
}
const imageData: MetadataImageModule = {
url: outputPath,
const imageData: Omit<MetadataImageModule, 'url'> = {
...(extension in imageExtMimeTypeMap && {
type: imageExtMimeTypeMap[extension as keyof typeof imageExtMimeTypeMap],
}),
......@@ -95,9 +104,23 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
}),
}
const stringifiedData = JSON.stringify(imageData)
return `\
import path from 'path'
import { interpolateDynamicPath } from 'next/dist/server/server-utils'
import { getNamedRouteRegex } from 'next/dist/shared/lib/router/utils/route-regex'
export default (props) => {
const pathname = ${JSON.stringify(route)}
const routeRegex = getNamedRouteRegex(pathname)
const route = interpolateDynamicPath(pathname, props.params, routeRegex)
return `export default ${stringifiedData};`
const imageData = ${JSON.stringify(imageData)};
return {
...imageData,
url: path.join(route, ${JSON.stringify(pageRoute)}),
}
}`
}
export const raw = true
......
......@@ -221,26 +221,27 @@ async function getDefinedMetadata(
async function collectStaticImagesFiles(
metadata: ComponentsType['metadata'],
props: any,
type: keyof NonNullable<ComponentsType['metadata']>
) {
if (!metadata?.[type]) return undefined
const iconPromises = metadata[type as 'icon' | 'apple'].map(
async (iconResolver: () => Promise<MetadataImageModule>) =>
interopDefault(await iconResolver())
async (imageModule: (p: any) => Promise<MetadataImageModule>) =>
interopDefault(await imageModule(props))
)
return iconPromises?.length > 0 ? await Promise.all(iconPromises) : undefined
}
async function resolveStaticMetadata(components: ComponentsType) {
async function resolveStaticMetadata(components: ComponentsType, props: any) {
const { metadata } = components
if (!metadata) return null
const [icon, apple, openGraph, twitter] = await Promise.all([
collectStaticImagesFiles(metadata, 'icon'),
collectStaticImagesFiles(metadata, 'apple'),
collectStaticImagesFiles(metadata, 'openGraph'),
collectStaticImagesFiles(metadata, 'twitter'),
collectStaticImagesFiles(metadata, props, 'icon'),
collectStaticImagesFiles(metadata, props, 'apple'),
collectStaticImagesFiles(metadata, props, 'openGraph'),
collectStaticImagesFiles(metadata, props, 'twitter'),
])
const staticMetadata = {
......@@ -271,7 +272,7 @@ export async function collectMetadata({
route += `/${modType}`
}
const staticFilesMetadata = await resolveStaticMetadata(loaderTree[2])
const staticFilesMetadata = await resolveStaticMetadata(loaderTree[2], props)
const metadataExport = mod
? await getDefinedMetadata(mod, props, route)
: null
......
......@@ -109,6 +109,15 @@ createNextDescribe(
)
})
it('should fill params into dynamic routes url of metadata images', async () => {
const $ = await next.render$('/dynamic/big')
const ogImageUrl = $('meta[property="og:image"]').attr('content')
expect(ogImageUrl).toMatch(hashRegex)
expect(ogImageUrl).toMatch('/dynamic/big/opengraph-image')
// should already normalize the parallel routes segment to url
expect(ogImageUrl).not.toContain('(group)')
})
it('should support params as argument in dynamic routes', async () => {
const bufferBig = await (
await next.fetch('/dynamic/big/opengraph-image')
......
......@@ -23,7 +23,7 @@ describe('app dir - metadata missing metadataBase', () => {
if (globalThis.isNextDev) {
it('should warning in development', async () => {
await next.start()
await fetchViaHTTP(next.url, '/')
await fetchViaHTTP(next.url, '/blog')
expect(next.cliOutput).toInclude(
'metadata.metadataBase is not set and fallbacks to "http://localhost:'
)
......@@ -35,7 +35,7 @@ describe('app dir - metadata missing metadataBase', () => {
it('should error in production', async () => {
await expect(next.start()).rejects.toThrow('next build failed')
expect(next.cliOutput).toInclude(
'metadata.metadataBase needs to be provided for resolving absolute URL: /opengraph-image?'
'metadata.metadataBase needs to be provided for resolving absolute URL: /blog/opengraph-image?'
)
})
}
......
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