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