Unverified Commit 44dc4efa authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix dynamic routes for generateImageMetadata (#48928)

* Fix the `generateImageMetadata` for non dynamic routes and related
`param` matching (Found during development)
* Fix dynamic routes with number suffix `(\d)` (Fixes #48689)
parent c94122dc
......@@ -106,9 +106,9 @@ export async function GET(_, ctx) {
const id = __metadata_id__[0]
const imageMetadata = generateImageMetadata ? await generateImageMetadata({ params }) : null
if (imageMetadata) {
const hasId = imageMetadata.some((item) => { item.id === id })
const hasId = imageMetadata.some((item) => item.id.toString() === id)
if (!hasId) {
return new NextResponse(null, {
return new NextResponse('Not Found', {
status: 404,
})
}
......@@ -140,7 +140,7 @@ export async function GET(_, ctx) {
const targetId = __metadata_id__[0]
id = sitemaps.find((item) => item.id.toString() === targetId)?.id
if (id == null) {
return new NextResponse(null, {
return new NextResponse('Not Found', {
status: 404,
})
}
......
import { isMetadataRoute, isMetadataRouteFile } from './is-metadata-route'
import path from '../../shared/lib/isomorphic/path'
import { djb2Hash } from '../../shared/lib/hash'
import { isDynamicRoute } from '../../shared/lib/router/utils'
/*
* If there's special convention like (...) or @ in the page path,
......@@ -30,42 +29,40 @@ export function getMetadataRouteSuffix(page: string) {
* @returns
*/
export function normalizeMetadataRoute(page: string) {
if (!isMetadataRoute(page)) {
return page
}
let route = page
let suffix = ''
if (isMetadataRoute(page)) {
if (route === '/robots') {
route += '.txt'
} else if (route === '/manifest') {
route += '.webmanifest'
} else if (route.endsWith('/sitemap')) {
route += '.xml'
} else {
// Remove the file extension, e.g. /route-path/robots.txt -> /route-path
const pathnamePrefix = page.slice(0, -(path.basename(page).length + 1))
suffix = getMetadataRouteSuffix(pathnamePrefix)
}
// Support both /<metadata-route.ext> and custom routes /<metadata-route>/route.ts.
// If it's a metadata file route, we need to append /[id]/route to the page.
if (!route.endsWith('/route')) {
const isStaticMetadataFile = isMetadataRouteFile(route, [], true)
const { dir, name: baseName, ext } = path.parse(route)
if (route === '/robots') {
route += '.txt'
} else if (route === '/manifest') {
route += '.webmanifest'
} else if (route.endsWith('/sitemap')) {
route += '.xml'
} else {
// Remove the file extension, e.g. /route-path/robots.txt -> /route-path
const pathnamePrefix = page.slice(0, -(path.basename(page).length + 1))
suffix = getMetadataRouteSuffix(pathnamePrefix)
}
// Support both /<metadata-route.ext> and custom routes /<metadata-route>/route.ts.
// If it's a metadata file route, we need to append /[id]/route to the page.
if (!route.endsWith('/route')) {
const isStaticMetadataFile = isMetadataRouteFile(page, [], true)
const { dir, name: baseName, ext } = path.parse(route)
// If it's dynamic routes, we need to append [[...__metadata_id__]] to the page;
// If it's static routes, we need to append nothing to the page.
// If its special routes like robots.txt and manifest.webmanifest, we leave them as static routes.
const isStaticRoute =
!isDynamicRoute(route) &&
(page.startsWith('/robots') ||
page.startsWith('/manifest') ||
isStaticMetadataFile)
const isStaticRoute =
page.startsWith('/robots') ||
page.startsWith('/manifest') ||
isStaticMetadataFile
route = path.posix.join(
dir,
`${baseName}${suffix ? `-${suffix}` : ''}${ext}`,
isStaticRoute ? '' : '[[...__metadata_id__]]',
'route'
)
}
route = path.posix.join(
dir,
`${baseName}${suffix ? `-${suffix}` : ''}${ext}`,
isStaticRoute ? '' : '[[...__metadata_id__]]',
'route'
)
}
return route
}
......@@ -43,7 +43,7 @@ export function isMetadataRouteFile(
new RegExp(
`^[\\\\/]robots${
withExtension
? `\\.${getExtensionRegexString(pageExtensions.concat('txt'))}`
? `\\.${getExtensionRegexString(pageExtensions.concat('txt'))}$`
: ''
}`
),
......@@ -52,7 +52,7 @@ export function isMetadataRouteFile(
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat('webmanifest', 'json')
)}`
)}$`
: ''
}`
),
......@@ -60,43 +60,43 @@ export function isMetadataRouteFile(
new RegExp(
`[\\\\/]sitemap${
withExtension
? `\\.${getExtensionRegexString(pageExtensions.concat('xml'))}`
? `\\.${getExtensionRegexString(pageExtensions.concat('xml'))}$`
: ''
}`
),
new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}${
`[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}\\d?${
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.icon.extensions)
)}`
)}$`
: ''
}`
),
new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}${
`[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}\\d?${
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.apple.extensions)
)}`
)}$`
: ''
}`
),
new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.openGraph.filename}${
`[\\\\/]${STATIC_METADATA_IMAGES.openGraph.filename}\\d?${
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.openGraph.extensions)
)}`
)}$`
: ''
}`
),
new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}${
`[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}\\d?${
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.twitter.extensions)
)}`
)}$`
: ''
}`
),
......
import { ImageResponse } from 'next/server'
export const alt = 'Open Graph'
export async function generateImageMetadata() {
return [
{
contentType: 'image/png',
size: { width: 1200, height: 600 },
id: 100,
},
{
contentType: 'image/png',
size: { width: 1200, height: 600 },
id: 101,
},
]
}
export default function og() {
return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 128,
background: 'lavender',
}}
>
Open Graph
</div>
)
)
}
......@@ -326,16 +326,25 @@ createNextDescribe(
it('should use localhost for local prod and fallback to deployment url when metadataBase is falsy', async () => {
const $ = await next.render$('/metadata-base/unset')
const twitterImage = $('meta[name="twitter:image"]').attr('content')
if (isNextDeploy) {
expect(twitterImage).toMatch(
/https:\/\/[\w-]+.vercel.app\/metadata-base\/unset\/twitter-image\.png/
const ogImages = $('meta[property="og:image"]')
expect(ogImages.length).toBe(2)
ogImages.each((_, ogImage) => {
const ogImageUrl = $(ogImage).attr('content')
expect(ogImageUrl).toMatch(
isNextDeploy
? /https:\/\/[\w-]+.vercel.app/
: /http:\/\/localhost:\d+/
)
} else {
expect(twitterImage).toMatch(
/http:\/\/localhost:\d+\/metadata-base\/unset\/twitter-image\.png/
expect(ogImageUrl).toMatch(
/\/metadata-base\/unset\/opengraph-image2\/10\d/
)
}
})
expect(twitterImage).toMatch(
isNextDeploy ? /https:\/\/[\w-]+.vercel.app/ : /http:\/\/localhost:\d+/
)
expect(twitterImage).toMatch(/\/metadata-base\/unset\/twitter-image\.png/)
})
if (isNextStart) {
......
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