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) { ...@@ -106,9 +106,9 @@ export async function GET(_, ctx) {
const id = __metadata_id__[0] const id = __metadata_id__[0]
const imageMetadata = generateImageMetadata ? await generateImageMetadata({ params }) : null const imageMetadata = generateImageMetadata ? await generateImageMetadata({ params }) : null
if (imageMetadata) { if (imageMetadata) {
const hasId = imageMetadata.some((item) => { item.id === id }) const hasId = imageMetadata.some((item) => item.id.toString() === id)
if (!hasId) { if (!hasId) {
return new NextResponse(null, { return new NextResponse('Not Found', {
status: 404, status: 404,
}) })
} }
...@@ -140,7 +140,7 @@ export async function GET(_, ctx) { ...@@ -140,7 +140,7 @@ export async function GET(_, ctx) {
const targetId = __metadata_id__[0] const targetId = __metadata_id__[0]
id = sitemaps.find((item) => item.id.toString() === targetId)?.id id = sitemaps.find((item) => item.id.toString() === targetId)?.id
if (id == null) { if (id == null) {
return new NextResponse(null, { return new NextResponse('Not Found', {
status: 404, status: 404,
}) })
} }
......
import { isMetadataRoute, isMetadataRouteFile } from './is-metadata-route' import { isMetadataRoute, isMetadataRouteFile } from './is-metadata-route'
import path from '../../shared/lib/isomorphic/path' import path from '../../shared/lib/isomorphic/path'
import { djb2Hash } from '../../shared/lib/hash' import { djb2Hash } from '../../shared/lib/hash'
import { isDynamicRoute } from '../../shared/lib/router/utils'
/* /*
* If there's special convention like (...) or @ in the page path, * If there's special convention like (...) or @ in the page path,
...@@ -30,9 +29,11 @@ export function getMetadataRouteSuffix(page: string) { ...@@ -30,9 +29,11 @@ export function getMetadataRouteSuffix(page: string) {
* @returns * @returns
*/ */
export function normalizeMetadataRoute(page: string) { export function normalizeMetadataRoute(page: string) {
if (!isMetadataRoute(page)) {
return page
}
let route = page let route = page
let suffix = '' let suffix = ''
if (isMetadataRoute(page)) {
if (route === '/robots') { if (route === '/robots') {
route += '.txt' route += '.txt'
} else if (route === '/manifest') { } else if (route === '/manifest') {
...@@ -47,17 +48,13 @@ export function normalizeMetadataRoute(page: string) { ...@@ -47,17 +48,13 @@ export function normalizeMetadataRoute(page: string) {
// Support both /<metadata-route.ext> and custom routes /<metadata-route>/route.ts. // 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 it's a metadata file route, we need to append /[id]/route to the page.
if (!route.endsWith('/route')) { if (!route.endsWith('/route')) {
const isStaticMetadataFile = isMetadataRouteFile(route, [], true) const isStaticMetadataFile = isMetadataRouteFile(page, [], true)
const { dir, name: baseName, ext } = path.parse(route) 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 = const isStaticRoute =
!isDynamicRoute(route) && page.startsWith('/robots') ||
(page.startsWith('/robots') ||
page.startsWith('/manifest') || page.startsWith('/manifest') ||
isStaticMetadataFile) isStaticMetadataFile
route = path.posix.join( route = path.posix.join(
dir, dir,
...@@ -66,6 +63,6 @@ export function normalizeMetadataRoute(page: string) { ...@@ -66,6 +63,6 @@ export function normalizeMetadataRoute(page: string) {
'route' 'route'
) )
} }
}
return route return route
} }
...@@ -43,7 +43,7 @@ export function isMetadataRouteFile( ...@@ -43,7 +43,7 @@ export function isMetadataRouteFile(
new RegExp( new RegExp(
`^[\\\\/]robots${ `^[\\\\/]robots${
withExtension withExtension
? `\\.${getExtensionRegexString(pageExtensions.concat('txt'))}` ? `\\.${getExtensionRegexString(pageExtensions.concat('txt'))}$`
: '' : ''
}` }`
), ),
...@@ -52,7 +52,7 @@ export function isMetadataRouteFile( ...@@ -52,7 +52,7 @@ export function isMetadataRouteFile(
withExtension withExtension
? `\\.${getExtensionRegexString( ? `\\.${getExtensionRegexString(
pageExtensions.concat('webmanifest', 'json') pageExtensions.concat('webmanifest', 'json')
)}` )}$`
: '' : ''
}` }`
), ),
...@@ -60,43 +60,43 @@ export function isMetadataRouteFile( ...@@ -60,43 +60,43 @@ export function isMetadataRouteFile(
new RegExp( new RegExp(
`[\\\\/]sitemap${ `[\\\\/]sitemap${
withExtension withExtension
? `\\.${getExtensionRegexString(pageExtensions.concat('xml'))}` ? `\\.${getExtensionRegexString(pageExtensions.concat('xml'))}$`
: '' : ''
}` }`
), ),
new RegExp( new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}${ `[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}\\d?${
withExtension withExtension
? `\\.${getExtensionRegexString( ? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.icon.extensions) pageExtensions.concat(STATIC_METADATA_IMAGES.icon.extensions)
)}` )}$`
: '' : ''
}` }`
), ),
new RegExp( new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}${ `[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}\\d?${
withExtension withExtension
? `\\.${getExtensionRegexString( ? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.apple.extensions) pageExtensions.concat(STATIC_METADATA_IMAGES.apple.extensions)
)}` )}$`
: '' : ''
}` }`
), ),
new RegExp( new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.openGraph.filename}${ `[\\\\/]${STATIC_METADATA_IMAGES.openGraph.filename}\\d?${
withExtension withExtension
? `\\.${getExtensionRegexString( ? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.openGraph.extensions) pageExtensions.concat(STATIC_METADATA_IMAGES.openGraph.extensions)
)}` )}$`
: '' : ''
}` }`
), ),
new RegExp( new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}${ `[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}\\d?${
withExtension withExtension
? `\\.${getExtensionRegexString( ? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.twitter.extensions) 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( ...@@ -326,16 +326,25 @@ createNextDescribe(
it('should use localhost for local prod and fallback to deployment url when metadataBase is falsy', async () => { 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 $ = await next.render$('/metadata-base/unset')
const twitterImage = $('meta[name="twitter:image"]').attr('content') const twitterImage = $('meta[name="twitter:image"]').attr('content')
const ogImages = $('meta[property="og:image"]')
if (isNextDeploy) {
expect(twitterImage).toMatch( expect(ogImages.length).toBe(2)
/https:\/\/[\w-]+.vercel.app\/metadata-base\/unset\/twitter-image\.png/ ogImages.each((_, ogImage) => {
const ogImageUrl = $(ogImage).attr('content')
expect(ogImageUrl).toMatch(
isNextDeploy
? /https:\/\/[\w-]+.vercel.app/
: /http:\/\/localhost:\d+/
) )
} else { expect(ogImageUrl).toMatch(
/\/metadata-base\/unset\/opengraph-image2\/10\d/
)
})
expect(twitterImage).toMatch( expect(twitterImage).toMatch(
/http:\/\/localhost:\d+\/metadata-base\/unset\/twitter-image\.png/ isNextDeploy ? /https:\/\/[\w-]+.vercel.app/ : /http:\/\/localhost:\d+/
) )
} expect(twitterImage).toMatch(/\/metadata-base\/unset\/twitter-image\.png/)
}) })
if (isNextStart) { 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