Skip to content

Commit

Permalink
Add /route subpath to metadata static routes (#47030)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
huozhi committed Mar 11, 2023
1 parent c110dfd commit fdfd9be
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 21 deletions.
9 changes: 7 additions & 2 deletions packages/next/src/build/entries.ts
Expand Up @@ -47,7 +47,7 @@ import { ServerRuntime } from '../../types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { encodeMatchers } from './webpack/loaders/next-middleware-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

Expand Down Expand Up @@ -99,7 +99,7 @@ export function createPagesMapping({
previousPages[pageKey] = pagePath
}

result[pageKey] = normalizePathSep(
const normalizedPath = normalizePathSep(
join(
pagesType === 'pages'
? PAGES_DIR_ALIAS
Expand All @@ -109,6 +109,11 @@ export function createPagesMapping({
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
},
{}
Expand Down
11 changes: 2 additions & 9 deletions packages/next/src/build/webpack/loaders/next-app-loader.ts
Expand Up @@ -64,17 +64,10 @@ async function createAppRouteCode({
pagePath: string
resolver: PathResolver
}): Promise<string> {
// Split based on any specific path separators (both `/` and `\`)...
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}`

const routePath = pagePath.replace(/[\\/]/, '/')
// This, when used with the resolver will give us the pathname to the built
// route handler file.
let resolvedPagePath = (await resolver(matchedPagePath))!
let resolvedPagePath = (await resolver(routePath))!

if (isMetadataRoute(name)) {
resolvedPagePath = `next-metadata-route-loader!${resolvedPagePath}`
Expand Down
14 changes: 7 additions & 7 deletions packages/next/src/lib/is-app-route-route.ts
@@ -1,21 +1,21 @@
import path from '../shared/lib/isomorphic/path'

export function isAppRouteRoute(route: string): boolean {
return route.endsWith('/route')
}

// Match routes that are metadata routes, e.g. /sitemap.xml, /favicon.<ext>, /<icon>.<ext>, etc.
// 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 {
// 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(/^\//, '')
return staticMetadataRoutes.includes(filename)
const filename = route
.replace(/^app\//, '')
.replace(/^\//, '')
.replace(/\/route$/, '')
return staticMetadataRoutes.some((r) => r.test(filename))
}

// Only match the static metadata files
// TODO-METADATA: support static metadata files under nested routes folders
export function isStaticMetadataRoute(resourcePath: string) {
const filename = path.basename(resourcePath)
return staticMetadataRoutes.includes(filename)
return staticMetadataRoutes.some((r) => r.test(resourcePath))
}
2 changes: 1 addition & 1 deletion packages/next/src/server/dev/hot-reloader.ts
Expand Up @@ -763,7 +763,7 @@ export default class HotReloader {
absolutePagePath: entryData.absolutePagePath,
rootDir: this.dir,
buildId: this.buildId,
bundlePath,
bundlePath: bundlePath,
config: this.config,
isDev: true,
page,
Expand Down
5 changes: 5 additions & 0 deletions test/e2e/app-dir/metadata/app/api/route.ts
@@ -0,0 +1,5 @@
import { NextResponse } from 'next/server'

export function GET() {
return new NextResponse('hello api route')
}
18 changes: 16 additions & 2 deletions test/e2e/app-dir/metadata/metadata.test.ts
Expand Up @@ -7,9 +7,9 @@ createNextDescribe(
'app dir - metadata',
{
files: __dirname,
skipDeployment: true,
// skipDeployment: true,
},
({ next, isNextDev }) => {
({ next, isNextDev, isNextStart }) => {
const getTitle = (browser: BrowserInterface) =>
browser.elementByCss('title').text()

Expand Down Expand Up @@ -658,6 +658,20 @@ createNextDescribe(
const invalidSitemapResponse = await next.fetch('/title/sitemap.xml')
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', () => {
Expand Down

0 comments on commit fdfd9be

Please sign in to comment.