Unverified Commit f5198b48 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[metadata] fix the metadata route like pages and refactor utils (#77264)

### What

- Fix the metadata route like pages rendering, e.g. `/sitemap/page.js` should still work properly rather than being treated as route
- Refactor metadata utils, should prefer using the file matcher rather than just checking the route or page path if possible to determine if it's metadata route

Previously the metadata regex didn't handle the route well. For example:

When it's not checking the end, `/opengraph-image-abc` can still be matched, but actually it's not a valid metadata route. This PR refines the route/file path regex matching for metadata entries and add more tests.

The underlayer helper - `isMetadataRouteFile`, you can use it to check if a file path is an metadata entry.
The helpers built on top of it:
- `isMetadataPage`: determine if a page path is metadata route, the input is more like a pathname.
- `isMetadataRoute`: determine if a route is metadata route, the input contains nextjs route suffix like `/route`.

We change the most of places to use `isMetadataRouteFile` if possible, since it's more accurate, especially when we check the static metadata routes, e.g. `/opengraph-image.png`, `/opengraph-image.js` will require the extension check and strict matching on file name convention.

Closes #77250 
Fixes #76747
parent 122c7d05
import path from 'path' import path from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
import { isMetadataRoute } from '../../../../lib/metadata/is-metadata-route' import {
DEFAULT_METADATA_ROUTE_EXTENSIONS,
isMetadataRouteFile,
} from '../../../../lib/metadata/is-metadata-route'
import type { NextConfig } from '../../../../server/config-shared' import type { NextConfig } from '../../../../server/config-shared'
import { AppBundlePathNormalizer } from '../../../../server/normalizers/built/app/app-bundle-path-normalizer' import { AppBundlePathNormalizer } from '../../../../server/normalizers/built/app/app-bundle-path-normalizer'
import { AppPathnameNormalizer } from '../../../../server/normalizers/built/app/app-pathname-normalizer' import { AppPathnameNormalizer } from '../../../../server/normalizers/built/app/app-pathname-normalizer'
...@@ -10,6 +13,7 @@ import type { PageExtensions } from '../../../page-extensions-type' ...@@ -10,6 +13,7 @@ import type { PageExtensions } from '../../../page-extensions-type'
import { getFilenameAndExtension } from '../next-metadata-route-loader' import { getFilenameAndExtension } from '../next-metadata-route-loader'
export async function createAppRouteCode({ export async function createAppRouteCode({
appDir,
name, name,
page, page,
pagePath, pagePath,
...@@ -17,6 +21,7 @@ export async function createAppRouteCode({ ...@@ -17,6 +21,7 @@ export async function createAppRouteCode({
pageExtensions, pageExtensions,
nextConfigOutput, nextConfigOutput,
}: { }: {
appDir: string
name: string name: string
page: string page: string
pagePath: string pagePath: string
...@@ -39,10 +44,16 @@ export async function createAppRouteCode({ ...@@ -39,10 +44,16 @@ export async function createAppRouteCode({
) )
} }
// If this is a metadata route, then we need to use the metadata loader for // If this is a metadata route file, then we need to use the metadata-loader
// the route to ensure that the route is generated. // for the route to ensure that the route is generated.
const fileBaseName = path.parse(resolvedPagePath).name const fileBaseName = path.parse(resolvedPagePath).name
if (isMetadataRoute(name) && fileBaseName !== 'route') { const appDirRelativePath = resolvedPagePath.slice(appDir.length)
const isMetadataEntryFile = isMetadataRouteFile(
appDirRelativePath,
DEFAULT_METADATA_ROUTE_EXTENSIONS,
true
)
if (isMetadataEntryFile) {
const { ext } = getFilenameAndExtension(resolvedPagePath) const { ext } = getFilenameAndExtension(resolvedPagePath)
const isDynamicRouteExtension = pageExtensions.includes(ext) const isDynamicRouteExtension = pageExtensions.includes(ext)
......
...@@ -666,6 +666,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -666,6 +666,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
if (isAppRouteRoute(name)) { if (isAppRouteRoute(name)) {
return createAppRouteCode({ return createAppRouteCode({
appDir,
// TODO: investigate if the local `page` is the same as the loaderOptions.page // TODO: investigate if the local `page` is the same as the loaderOptions.page
page: loaderOptions.page, page: loaderOptions.page,
name, name,
......
...@@ -43,7 +43,10 @@ import { PAGE_TYPES } from '../../../lib/page-types' ...@@ -43,7 +43,10 @@ import { PAGE_TYPES } from '../../../lib/page-types'
import { getModuleBuildInfo } from '../loaders/get-module-build-info' import { getModuleBuildInfo } from '../loaders/get-module-build-info'
import { getAssumedSourceType } from '../loaders/next-flight-loader' import { getAssumedSourceType } from '../loaders/next-flight-loader'
import { isAppRouteRoute } from '../../../lib/is-app-route-route' import { isAppRouteRoute } from '../../../lib/is-app-route-route'
import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route' import {
DEFAULT_METADATA_ROUTE_EXTENSIONS,
isMetadataRouteFile,
} from '../../../lib/metadata/is-metadata-route'
import type { MetadataRouteLoaderOptions } from '../loaders/next-metadata-route-loader' import type { MetadataRouteLoaderOptions } from '../loaders/next-metadata-route-loader'
import type { FlightActionEntryLoaderActions } from '../loaders/next-flight-action-entry-loader' import type { FlightActionEntryLoaderActions } from '../loaders/next-flight-action-entry-loader'
...@@ -346,13 +349,27 @@ export class FlightClientEntryPlugin { ...@@ -346,13 +349,27 @@ export class FlightClientEntryPlugin {
: entryRequest : entryRequest
// Replace file suffix as `.js` will be added. // Replace file suffix as `.js` will be added.
// bundlePath will have app/ prefix but not src/.
// e.g. src/app/foo/page.js -> app/foo/page
let bundlePath = normalizePathSep( let bundlePath = normalizePathSep(
relativeRequest.replace(/\.[^.\\/]+$/, '').replace(/^src[\\/]/, '') relativeRequest.replace(/\.[^.\\/]+$/, '').replace(/^src[\\/]/, '')
) )
// For metadata routes, the entry name can be used as the bundle path, // For metadata routes, the entry name can be used as the bundle path,
// as it has been normalized already. // as it has been normalized already.
if (isMetadataRoute(bundlePath)) { // e.g.
// When `relativeRequest` is 'src/app/sitemap.js',
// `appDirRelativeRequest` will be '/sitemap.js'
// then `isMetadataEntryFile` will be `true`
const appDirRelativeRequest = relativeRequest
.replace(/^src[\\/]/, '')
.replace(/^app[\\/]/, '/')
const isMetadataEntryFile = isMetadataRouteFile(
appDirRelativeRequest,
DEFAULT_METADATA_ROUTE_EXTENSIONS,
true
)
if (isMetadataEntryFile) {
bundlePath = name bundlePath = name
} }
......
...@@ -18,7 +18,7 @@ import picomatch from 'next/dist/compiled/picomatch' ...@@ -18,7 +18,7 @@ import picomatch from 'next/dist/compiled/picomatch'
import { getModuleBuildInfo } from '../loaders/get-module-build-info' import { getModuleBuildInfo } from '../loaders/get-module-build-info'
import { getPageFilePath } from '../../entries' import { getPageFilePath } from '../../entries'
import { resolveExternal } from '../../handle-externals' import { resolveExternal } from '../../handle-externals'
import { isStaticMetadataRoutePage } from '../../../lib/metadata/is-metadata-route' import { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route'
import { getCompilationSpan } from '../utils' import { getCompilationSpan } from '../utils'
const PLUGIN_NAME = 'TraceEntryPointsPlugin' const PLUGIN_NAME = 'TraceEntryPointsPlugin'
...@@ -243,7 +243,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -243,7 +243,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
const entryIsStaticMetadataRoute = const entryIsStaticMetadataRoute =
appDirRelativeEntryPath && appDirRelativeEntryPath &&
isStaticMetadataRoutePage(appDirRelativeEntryPath) isMetadataRouteFile(appDirRelativeEntryPath, [], true)
// Include the client reference manifest in the trace, but not for // Include the client reference manifest in the trace, but not for
// static metadata routes, for which we don't generate those. // static metadata routes, for which we don't generate those.
......
...@@ -23,7 +23,7 @@ import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error' ...@@ -23,7 +23,7 @@ import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { hasNextSupport } from '../../server/ci-info' import { hasNextSupport } from '../../server/ci-info'
import { isStaticGenEnabled } from '../../server/route-modules/app-route/helpers/is-static-gen-enabled' import { isStaticGenEnabled } from '../../server/route-modules/app-route/helpers/is-static-gen-enabled'
import type { ExperimentalConfig } from '../../server/config-shared' import type { ExperimentalConfig } from '../../server/config-shared'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route' import { isMetadataRoute } from '../../lib/metadata/is-metadata-route'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { AfterRunner } from '../../server/after/run-with-after' import { AfterRunner } from '../../server/after/run-with-after'
...@@ -101,13 +101,13 @@ export async function exportAppRoute( ...@@ -101,13 +101,13 @@ export async function exportAppRoute(
try { try {
const userland = module.userland const userland = module.userland
// we don't bail from the static optimization for // we don't bail from the static optimization for
// metadata routes // metadata routes, since it's app-route we can always append /route suffix.
const normalizedPage = normalizeAppPath(page) const routePath = normalizeAppPath(page) + '/route'
const isMetadataRoute = isMetadataRouteFile(normalizedPage, [], false) const isPageMetadataRoute = isMetadataRoute(routePath)
if ( if (
!isStaticGenEnabled(userland) && !isStaticGenEnabled(userland) &&
!isMetadataRoute && !isPageMetadataRoute &&
// We don't disable static gen when dynamicIO is enabled because we // We don't disable static gen when dynamicIO is enabled because we
// expect that anything dynamic in the GET handler will make it dynamic // expect that anything dynamic in the GET handler will make it dynamic
// and thus avoid the cache surprises that led to us removing static gen // and thus avoid the cache surprises that led to us removing static gen
......
import { isMetadataRoute } from './is-metadata-route' import { isMetadataPage } from './is-metadata-route'
import path from '../../shared/lib/isomorphic/path' import path from '../../shared/lib/isomorphic/path'
import { interpolateDynamicPath } from '../../server/server-utils' import { interpolateDynamicPath } from '../../server/server-utils'
import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex'
...@@ -83,7 +83,7 @@ export function fillMetadataSegment( ...@@ -83,7 +83,7 @@ export function fillMetadataSegment(
* @returns * @returns
*/ */
export function normalizeMetadataRoute(page: string) { export function normalizeMetadataRoute(page: string) {
if (!isMetadataRoute(page)) { if (!isMetadataPage(page)) {
return page return page
} }
let route = page let route = page
......
import { getExtensionRegexString } from './is-metadata-route' import {
getExtensionRegexString,
isMetadataRouteFile,
isMetadataRoute,
isMetadataPage,
} from './is-metadata-route'
describe('getExtensionRegexString', () => { describe('getExtensionRegexString', () => {
function createExtensionMatchRegex( function createExtensionMatchRegex(
...@@ -54,3 +59,99 @@ describe('getExtensionRegexString', () => { ...@@ -54,3 +59,99 @@ describe('getExtensionRegexString', () => {
}) })
}) })
}) })
describe('isMetadataRouteFile', () => {
describe('match route - without extension', () => {
it('should match metadata route page paths', () => {
expect(isMetadataRouteFile('/icons/descriptor/page', [], false)).toBe(
false
)
expect(isMetadataRouteFile('/foo/icon', [], false)).toBe(true)
expect(isMetadataRouteFile('/foo/opengraph-image', [], false)).toBe(true)
expect(isMetadataRouteFile('/foo/sitemap.xml', [], false)).toBe(true)
// group routes
expect(
isMetadataRouteFile('/foo/opengraph-image-abc123', [], false)
).toBe(true)
// These pages are not normalized from actual entry files
expect(isMetadataRouteFile('/foo/sitemap/0.xml', [], false)).toBe(false)
expect(
isMetadataRouteFile('/foo/opengraph-image-abc12313333', [], false)
).toBe(false)
})
})
describe('match file - with extension', () => {
it('should match static metadata route files', () => {
expect(isMetadataRouteFile('/icons/descriptor/page', [], true)).toBe(
false
)
expect(isMetadataRouteFile('/foo/icon.png', [], true)).toBe(true)
expect(isMetadataRouteFile('/bar/opengraph-image.jpg', [], true)).toBe(
true
)
expect(isMetadataRouteFile('/favicon.ico', [], true)).toBe(true)
expect(isMetadataRouteFile('/robots.txt', [], true)).toBe(true)
expect(isMetadataRouteFile('/manifest.json', [], true)).toBe(true)
expect(isMetadataRouteFile('/sitemap.xml', [], true)).toBe(true)
})
it('should match dynamic metadata routes', () => {
// with dynamic extensions, passing the 2nd arg: such as ['tsx', 'ts']
expect(isMetadataRouteFile('/foo/icon.js', ['tsx', 'ts'], true)).toBe(
false
)
expect(isMetadataRouteFile('/foo/icon.ts', ['tsx', 'ts'], true)).toBe(
true
)
expect(
isMetadataRouteFile('/foo/icon.tsx', ['js', 'jsx', 'tsx', 'ts'], true)
).toBe(true)
})
})
})
describe('isMetadataRoute', () => {
it('should require suffix for metadata routes', () => {
expect(isMetadataRoute('/icon')).toBe(false)
expect(isMetadataRoute('/icon/route')).toBe(true)
expect(isMetadataRoute('/opengraph-image')).toBe(false)
expect(isMetadataRoute('/opengraph-image/route')).toBe(true)
})
it('should match metadata routes', () => {
expect(isMetadataRoute('/app/robots/route')).toBe(true)
expect(isMetadataRoute('/robots/route')).toBe(true)
expect(isMetadataRoute('/sitemap/[__metadata_id__]/route')).toBe(true)
expect(isMetadataRoute('/app/sitemap/page')).toBe(false)
expect(isMetadataRoute('/icon-a102f4/route')).toBe(true)
})
it('should match grouped metadata routes', () => {
expect(isMetadataRoute('/opengraph-image-1ow20b/route')).toBe(true)
expect(isMetadataRoute('/foo/icon2-1ow20b/route')).toBe(true)
})
it('should support metadata variant numeric suffix', () => {
expect(isMetadataRoute('/icon0/route')).toBe(true)
expect(isMetadataRoute('/opengraph-image1/route')).toBe(true)
expect(isMetadataRoute('/foo/icon0-a120ff/route')).toBe(true)
expect(isMetadataRoute('/foo/icon0-a120ff3/route')).toBe(false)
})
})
describe('isMetadataPage', () => {
it('should match metadata page path', () => {
expect(isMetadataPage('/sitemap.xml')).toBe(true)
expect(isMetadataPage('/favicon.ico')).toBe(true)
expect(isMetadataPage('/manifest.json')).toBe(true)
expect(isMetadataPage('/robots.txt')).toBe(true)
})
it('should not match app router page path or error boundary path', () => {
expect(isMetadataPage('/icon/page')).toBe(false)
expect(isMetadataPage('/icon/route')).toBe(false)
expect(isMetadataPage('/icon/error')).toBe(false)
expect(isMetadataPage('/icon/not-found')).toBe(false)
})
})
import type { PageExtensions } from '../../build/page-extensions-type' import type { PageExtensions } from '../../build/page-extensions-type'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { isAppRouteRoute } from '../is-app-route-route' import { isAppRouteRoute } from '../is-app-route-route'
export const STATIC_METADATA_IMAGES = { export const STATIC_METADATA_IMAGES = {
...@@ -27,7 +28,7 @@ export const STATIC_METADATA_IMAGES = { ...@@ -27,7 +28,7 @@ export const STATIC_METADATA_IMAGES = {
// Match routes that are metadata routes, e.g. /sitemap.xml, /favicon.<ext>, /<icon>.<ext>, etc. // Match routes that are metadata routes, e.g. /sitemap.xml, /favicon.<ext>, /<icon>.<ext>, etc.
// TODO-METADATA: support more metadata routes with more extensions // TODO-METADATA: support more metadata routes with more extensions
const defaultExtensions = ['js', 'jsx', 'ts', 'tsx'] export const DEFAULT_METADATA_ROUTE_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx']
// Match the file extension with the dynamic multi-routes extensions // Match the file extension with the dynamic multi-routes extensions
// e.g. ([xml, js], null) -> can match `/sitemap.xml/route`, `sitemap.js/route` // e.g. ([xml, js], null) -> can match `/sitemap.xml/route`, `sitemap.js/route`
...@@ -38,98 +39,84 @@ export const getExtensionRegexString = ( ...@@ -38,98 +39,84 @@ export const getExtensionRegexString = (
) => { ) => {
// If there's no possible multi dynamic routes, will not match any <name>[].<ext> files // If there's no possible multi dynamic routes, will not match any <name>[].<ext> files
if (!dynamicExtensions || dynamicExtensions.length === 0) { if (!dynamicExtensions || dynamicExtensions.length === 0) {
return `\\.(?:${staticExtensions.join('|')})` return `(\\.(?:${staticExtensions.join('|')}))`
} }
return `(?:\\.(${staticExtensions.join('|')})|((\\[\\])?\\.(${dynamicExtensions.join('|')})))` return `(?:\\.(${staticExtensions.join('|')})|(\\.(${dynamicExtensions.join('|')})))`
} }
// When you only pass the file extension as `[]`, it will only match the static convention files /**
// e.g. /robots.txt, /sitemap.xml, /favicon.ico, /manifest.json * Determine if the file is a metadata route file entry
// When you pass the file extension as `['js', 'jsx', 'ts', 'tsx']`, it will also match the dynamic convention files * @param appDirRelativePath the relative file path to app/
// e.g. /robots.js, /sitemap.tsx, /favicon.jsx, /manifest.ts * @param pageExtensions the js extensions, such as ['js', 'jsx', 'ts', 'tsx']
// When `withExtension` is false, it will match the static convention files without the extension, by default it's true * @param strictlyMatchExtensions if it's true, match the file with page extension, otherwise match the file with default corresponding extension
// e.g. /robots, /sitemap, /favicon, /manifest, use to match dynamic API routes like app/robots.ts * @returns {boolean} if the file is a metadata route file
*/
export function isMetadataRouteFile( export function isMetadataRouteFile(
appDirRelativePath: string, appDirRelativePath: string,
pageExtensions: PageExtensions, pageExtensions: PageExtensions,
withExtension: boolean strictlyMatchExtensions: boolean
) { ) {
// End with the extension or optional to have the extension
// When strictlyMatchExtensions is true, it's used for match file path;
// When strictlyMatchExtensions, the dynamic extension is skipped but
// static extension is kept, which is usually used for matching route path.
const trailingMatcher = (strictlyMatchExtensions ? '' : '?') + '$'
// Match the optional variants like /opengraph-image2, /icon-a102f4.png, etc.
const variantsMatcher = '\\d?'
// The -\w{6} is the suffix that normalized from group routes;
const groupSuffix = strictlyMatchExtensions ? '' : '(-\\w{6})?'
const suffixMatcher = `${variantsMatcher}${groupSuffix}`
const metadataRouteFilesRegex = [ const metadataRouteFilesRegex = [
new RegExp( new RegExp(
`^[\\\\/]robots${ `^[\\\\/]robots${getExtensionRegexString(
withExtension pageExtensions.concat('txt'),
? `${getExtensionRegexString(pageExtensions.concat('txt'), null)}$` null
: '' )}${trailingMatcher}`
}`
), ),
new RegExp( new RegExp(
`^[\\\\/]manifest${ `^[\\\\/]manifest${getExtensionRegexString(
withExtension pageExtensions.concat('webmanifest', 'json'),
? `${getExtensionRegexString( null
pageExtensions.concat('webmanifest', 'json'), )}${trailingMatcher}`
null
)}$`
: ''
}`
), ),
new RegExp(`^[\\\\/]favicon\\.ico$`), new RegExp(`^[\\\\/]favicon\\.ico$`),
new RegExp( new RegExp(
`[\\\\/]sitemap${ `[\\\\/]sitemap${getExtensionRegexString(['xml'], pageExtensions)}${trailingMatcher}`
withExtension
? `${getExtensionRegexString(['xml'], pageExtensions)}$`
: ''
}`
), ),
new RegExp( new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}\\d?${ `[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}${suffixMatcher}${getExtensionRegexString(
withExtension STATIC_METADATA_IMAGES.icon.extensions,
? `${getExtensionRegexString( pageExtensions
STATIC_METADATA_IMAGES.icon.extensions, )}${trailingMatcher}`
pageExtensions
)}$`
: ''
}`
), ),
new RegExp( new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}\\d?${ `[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}${suffixMatcher}${getExtensionRegexString(
withExtension STATIC_METADATA_IMAGES.apple.extensions,
? `${getExtensionRegexString( pageExtensions
STATIC_METADATA_IMAGES.apple.extensions, )}${trailingMatcher}`
pageExtensions
)}$`
: ''
}`
), ),
new RegExp( new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.openGraph.filename}\\d?${ `[\\\\/]${STATIC_METADATA_IMAGES.openGraph.filename}${suffixMatcher}${getExtensionRegexString(
withExtension STATIC_METADATA_IMAGES.openGraph.extensions,
? `${getExtensionRegexString( pageExtensions
STATIC_METADATA_IMAGES.openGraph.extensions, )}${trailingMatcher}`
pageExtensions
)}$`
: ''
}`
), ),
new RegExp( new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}\\d?${ `[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}${suffixMatcher}${getExtensionRegexString(
withExtension STATIC_METADATA_IMAGES.twitter.extensions,
? `${getExtensionRegexString( pageExtensions
STATIC_METADATA_IMAGES.twitter.extensions, )}${trailingMatcher}`
pageExtensions
)}$`
: ''
}`
), ),
] ]
const normalizedAppDirRelativePath = normalizePathSep(appDirRelativePath) const normalizedAppDirRelativePath = normalizePathSep(appDirRelativePath)
return metadataRouteFilesRegex.some((r) => const matched = metadataRouteFilesRegex.some((r) =>
r.test(normalizedAppDirRelativePath) r.test(normalizedAppDirRelativePath)
) )
}
export function isStaticMetadataRoutePage(appDirRelativePath: string) { return matched
return isMetadataRouteFile(appDirRelativePath, [], true)
} }
// Check if the route is a static metadata route, with /route suffix // Check if the route is a static metadata route, with /route suffix
...@@ -137,31 +124,60 @@ export function isStaticMetadataRoutePage(appDirRelativePath: string) { ...@@ -137,31 +124,60 @@ export function isStaticMetadataRoutePage(appDirRelativePath: string) {
// But skip the text routes like robots.txt since they might also be dynamic. // But skip the text routes like robots.txt since they might also be dynamic.
// Checking route path is not enough to determine if text routes is dynamic. // Checking route path is not enough to determine if text routes is dynamic.
export function isStaticMetadataRoute(route: string) { export function isStaticMetadataRoute(route: string) {
const pathname = route.slice(0, -'/route'.length) // extract ext with regex
return ( const pathname = route.replace(/\/route$/, '')
const matched =
isAppRouteRoute(route) && isAppRouteRoute(route) &&
isStaticMetadataRoutePage(pathname) && isMetadataRouteFile(pathname, [], true) &&
// These routes can either be built by static or dynamic entrypoints, // These routes can either be built by static or dynamic entrypoints,
// so we assume they're dynamic // so we assume they're dynamic
pathname !== '/robots.txt' && pathname !== '/robots.txt' &&
pathname !== '/manifest.webmanifest' && pathname !== '/manifest.webmanifest' &&
!pathname.endsWith('/sitemap.xml') !pathname.endsWith('/sitemap.xml')
)
return matched
}
/**
* Determine if a page or pathname is a metadata page.
*
* The input is a page or pathname, which can be with or without page suffix /foo/page or /foo.
* But it will not contain the /route suffix.
*
* .e.g
* /robots -> true
* /sitemap -> true
* /foo -> false
*/
export function isMetadataPage(page: string) {
const matched = !isAppRouteRoute(page) && isMetadataRouteFile(page, [], false)
return matched
} }
/* /*
* Remove the 'app' prefix or '/route' suffix, only check the route name since they're only allowed in root app directory * Determine if a Next.js route is a metadata route.
* `route` will has a route suffix.
*
* e.g. * e.g.
* /app/robots -> /robots * /app/robots/route -> true
* app/robots -> /robots * /robots/route -> true
* /robots -> /robots * /sitemap/[__metadata_id__]/route -> true
* /app/sitemap/page -> false
* /icon-a102f4/route -> true
*/ */
export function isMetadataRoute(route: string): boolean { export function isMetadataRoute(route: string): boolean {
let page = route.replace(/^\/?app\//, '').replace(/\/route$/, '') let page = normalizeAppPath(route)
.replace(/^\/?app\//, '')
// Remove the dynamic route id
.replace('/[__metadata_id__]', '')
// Remove the /route suffix
.replace(/\/route$/, '')
if (page[0] !== '/') page = '/' + page if (page[0] !== '/') page = '/' + page
return ( const matched = isAppRouteRoute(route) && isMetadataRouteFile(page, [], false)
!page.endsWith('/page') &&
isMetadataRouteFile(page, defaultExtensions, false) return matched
)
} }
'use client'
export default function Error() {
return <p>Error</p>
}
export default function Page() {
return <h1>Icon</h1>
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
export default function Error() {
return <p>Error</p>
}
export default function Page() {
return <h1>Sitemap</h1>
}
import { nextTestSetup } from 'e2e-utils'
import { assertNoRedbox } from 'next-test-utils'
describe('metadata-route-like-pages', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should able to visit sitemap page', async () => {
const browser = await next.browser('/sitemap')
await assertNoRedbox(browser)
expect(await browser.elementByCss('h1').text()).toBe('Sitemap')
})
it('should able to visit icon page', async () => {
const browser = await next.browser('/icon')
await assertNoRedbox(browser)
expect(await browser.elementByCss('h1').text()).toBe('Icon')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
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