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

Add /route subpath to metadata static routes (#47030)

Set the output bundle file path to `/<metadata route>/route.js` to align with other custom app routes, in order to make it easier being handled by app routes in both nextjs and vercel 
parent c110dfd5
...@@ -47,7 +47,7 @@ import { ServerRuntime } from '../../types' ...@@ -47,7 +47,7 @@ import { ServerRuntime } from '../../types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { encodeMatchers } from './webpack/loaders/next-middleware-loader' import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute, isMetadataRoute } from '../lib/is-app-route-route'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
...@@ -99,7 +99,7 @@ export function createPagesMapping({ ...@@ -99,7 +99,7 @@ export function createPagesMapping({
previousPages[pageKey] = pagePath previousPages[pageKey] = pagePath
} }
result[pageKey] = normalizePathSep( const normalizedPath = normalizePathSep(
join( join(
pagesType === 'pages' pagesType === 'pages'
? PAGES_DIR_ALIAS ? PAGES_DIR_ALIAS
...@@ -109,6 +109,11 @@ export function createPagesMapping({ ...@@ -109,6 +109,11 @@ export function createPagesMapping({
pagePath pagePath
) )
) )
// Map metadata routes to /<metadata-route>/route, e.g. /robots.txt/route.
// This is to mark it as app route path that could be picked up like other custom app routes.
result[isMetadataRoute(pageKey) ? `${pageKey}/route` : pageKey] =
normalizedPath
return result return result
}, },
{} {}
......
...@@ -64,17 +64,10 @@ async function createAppRouteCode({ ...@@ -64,17 +64,10 @@ async function createAppRouteCode({
pagePath: string pagePath: string
resolver: PathResolver resolver: PathResolver
}): Promise<string> { }): Promise<string> {
// Split based on any specific path separators (both `/` and `\`)... const routePath = pagePath.replace(/[\\/]/, '/')
const routeName = name.split('/').pop()!
const splittedPath = pagePath.split(/[\\/]/)
// Then join all but the last part with the same separator, `/`...
const segmentPath = splittedPath.slice(0, -1).join('/')
// Then add the `/route` suffix...
const matchedPagePath = `${segmentPath}/${routeName}`
// This, when used with the resolver will give us the pathname to the built // This, when used with the resolver will give us the pathname to the built
// route handler file. // route handler file.
let resolvedPagePath = (await resolver(matchedPagePath))! let resolvedPagePath = (await resolver(routePath))!
if (isMetadataRoute(name)) { if (isMetadataRoute(name)) {
resolvedPagePath = `next-metadata-route-loader!${resolvedPagePath}` resolvedPagePath = `next-metadata-route-loader!${resolvedPagePath}`
......
import path from '../shared/lib/isomorphic/path'
export function isAppRouteRoute(route: string): boolean { export function isAppRouteRoute(route: string): boolean {
return route.endsWith('/route') return route.endsWith('/route')
} }
// 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 staticMetadataRoutes = ['robots.txt', 'sitemap.xml', 'favicon.ico'] const staticMetadataRoutes = [/robots\.txt/, /sitemap\.xml/, /favicon\.ico/]
export function isMetadataRoute(route: string): boolean { export function isMetadataRoute(route: string): boolean {
// Remove the 'app/' or '/' prefix, only check the route name since they're only allowed in root app directory // Remove the 'app/' or '/' prefix, only check the route name since they're only allowed in root app directory
const filename = route.replace(/^app\//, '').replace(/^\//, '') const filename = route
return staticMetadataRoutes.includes(filename) .replace(/^app\//, '')
.replace(/^\//, '')
.replace(/\/route$/, '')
return staticMetadataRoutes.some((r) => r.test(filename))
} }
// Only match the static metadata files // Only match the static metadata files
// TODO-METADATA: support static metadata files under nested routes folders // TODO-METADATA: support static metadata files under nested routes folders
export function isStaticMetadataRoute(resourcePath: string) { export function isStaticMetadataRoute(resourcePath: string) {
const filename = path.basename(resourcePath) return staticMetadataRoutes.some((r) => r.test(resourcePath))
return staticMetadataRoutes.includes(filename)
} }
...@@ -763,7 +763,7 @@ export default class HotReloader { ...@@ -763,7 +763,7 @@ export default class HotReloader {
absolutePagePath: entryData.absolutePagePath, absolutePagePath: entryData.absolutePagePath,
rootDir: this.dir, rootDir: this.dir,
buildId: this.buildId, buildId: this.buildId,
bundlePath, bundlePath: bundlePath,
config: this.config, config: this.config,
isDev: true, isDev: true,
page, page,
......
import { NextResponse } from 'next/server'
export function GET() {
return new NextResponse('hello api route')
}
...@@ -7,9 +7,9 @@ createNextDescribe( ...@@ -7,9 +7,9 @@ createNextDescribe(
'app dir - metadata', 'app dir - metadata',
{ {
files: __dirname, files: __dirname,
skipDeployment: true, // skipDeployment: true,
}, },
({ next, isNextDev }) => { ({ next, isNextDev, isNextStart }) => {
const getTitle = (browser: BrowserInterface) => const getTitle = (browser: BrowserInterface) =>
browser.elementByCss('title').text() browser.elementByCss('title').text()
...@@ -658,6 +658,20 @@ createNextDescribe( ...@@ -658,6 +658,20 @@ createNextDescribe(
const invalidSitemapResponse = await next.fetch('/title/sitemap.xml') const invalidSitemapResponse = await next.fetch('/title/sitemap.xml')
expect(invalidSitemapResponse.status).toBe(404) expect(invalidSitemapResponse.status).toBe(404)
}) })
if (isNextStart) {
it('should build favicon.ico as a custom route', async () => {
const appPathsManifest = JSON.parse(
await next.readFile('.next/server/app-paths-manifest.json')
)
expect(appPathsManifest['/robots.txt/route']).toBe(
'app/robots.txt/route.js'
)
expect(appPathsManifest['/sitemap.xml/route']).toBe(
'app/sitemap.xml/route.js'
)
})
}
}) })
describe('react cache', () => { describe('react cache', () => {
......
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