Unverified Commit 5831d0c1 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix static metadata routes runtime when root layout is in edge runtime (#50351)

Since the static metadata routes should always be static that can be
optimized, they should be marked as default runtime (or basically no
runtime). This PR change the runtime detection, if it's a static
metadata route file, its runtime will be erased.

So that it won't be picked up by `edge-app-route-loader` and then by
`next-image-loader` which emits the unexpected static file

Fixes NEXT-1238
parent 26835bdb
...@@ -54,6 +54,7 @@ import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route' ...@@ -54,6 +54,7 @@ import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader' import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader'
import { isInternalPathname } from '../lib/is-internal-pathname' import { isInternalPathname } from '../lib/is-internal-pathname'
import { isStaticMetadataRouteFile } from '../lib/metadata/is-metadata-route'
export async function getStaticInfoIncludingLayouts({ export async function getStaticInfoIncludingLayouts({
isInsideAppDir, isInsideAppDir,
...@@ -128,6 +129,13 @@ export async function getStaticInfoIncludingLayouts({ ...@@ -128,6 +129,13 @@ export async function getStaticInfoIncludingLayouts({
if (pageStaticInfo.preferredRegion) { if (pageStaticInfo.preferredRegion) {
staticInfo.preferredRegion = pageStaticInfo.preferredRegion staticInfo.preferredRegion = pageStaticInfo.preferredRegion
} }
// if it's static metadata route, don't inherit runtime from layout
const relativePath = pageFilePath.replace(appDir, '')
if (isStaticMetadataRouteFile(relativePath)) {
delete staticInfo.runtime
delete staticInfo.preferredRegion
}
} }
return staticInfo return staticInfo
} }
......
...@@ -14,6 +14,7 @@ import { ...@@ -14,6 +14,7 @@ import {
RSC_ACTION_PROXY_ALIAS, RSC_ACTION_PROXY_ALIAS,
RSC_ACTION_CLIENT_WRAPPER_ALIAS, RSC_ACTION_CLIENT_WRAPPER_ALIAS,
RSC_ACTION_VALIDATE_ALIAS, RSC_ACTION_VALIDATE_ALIAS,
WEBPACK_RESOURCE_QUERIES,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js' import { CustomRoutes } from '../lib/load-custom-routes.js'
...@@ -64,7 +65,6 @@ import { AppBuildManifestPlugin } from './webpack/plugins/app-build-manifest-plu ...@@ -64,7 +65,6 @@ import { AppBuildManifestPlugin } from './webpack/plugins/app-build-manifest-plu
import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin' import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin'
import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin' import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin'
import { getSupportedBrowsers } from './utils' import { getSupportedBrowsers } from './utils'
import { METADATA_RESOURCE_QUERY } from './webpack/loaders/metadata/discover'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
type ClientEntries = { type ClientEntries = {
...@@ -1942,7 +1942,9 @@ export default async function getBaseWebpackConfig( ...@@ -1942,7 +1942,9 @@ export default async function getBaseWebpackConfig(
// be in the SSR layer — here we convert the actual page request to // be in the SSR layer — here we convert the actual page request to
// the RSC layer via a webpack rule. // the RSC layer via a webpack rule.
{ {
resourceQuery: /__edge_ssr_entry__/, resourceQuery: new RegExp(
WEBPACK_RESOURCE_QUERIES.edgeSSREntry
),
layer: WEBPACK_LAYERS.server, layer: WEBPACK_LAYERS.server,
}, },
] ]
...@@ -2039,7 +2041,9 @@ export default async function getBaseWebpackConfig( ...@@ -2039,7 +2041,9 @@ export default async function getBaseWebpackConfig(
}, },
{ {
test: codeCondition.test, test: codeCondition.test,
resourceQuery: /__edge_ssr_entry__/, resourceQuery: new RegExp(
WEBPACK_RESOURCE_QUERIES.edgeSSREntry
),
use: swcLoaderForServerLayer, use: swcLoaderForServerLayer,
}, },
{ {
...@@ -2087,7 +2091,9 @@ export default async function getBaseWebpackConfig( ...@@ -2087,7 +2091,9 @@ export default async function getBaseWebpackConfig(
loader: 'next-image-loader', loader: 'next-image-loader',
issuer: { not: regexLikeCss }, issuer: { not: regexLikeCss },
dependency: { not: ['url'] }, dependency: { not: ['url'] },
resourceQuery: { not: [METADATA_RESOURCE_QUERY] }, resourceQuery: {
not: [new RegExp(WEBPACK_RESOURCE_QUERIES.metadata)],
},
options: { options: {
isServer: isNodeServer || isEdgeServer, isServer: isNodeServer || isEdgeServer,
isDev: dev, isDev: dev,
......
...@@ -6,11 +6,10 @@ import type { ...@@ -6,11 +6,10 @@ import type {
import path from 'path' import path from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { STATIC_METADATA_IMAGES } from '../../../../lib/metadata/is-metadata-route' import { STATIC_METADATA_IMAGES } from '../../../../lib/metadata/is-metadata-route'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
const METADATA_TYPE = 'metadata' const METADATA_TYPE = 'metadata'
export const METADATA_RESOURCE_QUERY = '?__next_metadata'
// Produce all compositions with filename (icon, apple-icon, etc.) with extensions (png, jpg, etc.) // Produce all compositions with filename (icon, apple-icon, etc.) with extensions (png, jpg, etc.)
async function enumMetadataFiles( async function enumMetadataFiles(
dir: string, dir: string,
...@@ -129,7 +128,7 @@ export async function createStaticMetadataFromRoute( ...@@ -129,7 +128,7 @@ export async function createStaticMetadataFromRoute(
basePath, basePath,
pageExtensions, pageExtensions,
} }
)}!${filepath}${METADATA_RESOURCE_QUERY}` )}!${filepath}?${WEBPACK_RESOURCE_QUERIES.metadata}`
const imageModule = `(async (props) => (await import(/* webpackMode: "eager" */ ${JSON.stringify( const imageModule = `(async (props) => (await import(/* webpackMode: "eager" */ ${JSON.stringify(
imageModuleImportSource imageModuleImportSource
......
...@@ -9,11 +9,10 @@ import { NODE_RESOLVE_OPTIONS } from '../../webpack-config' ...@@ -9,11 +9,10 @@ import { NODE_RESOLVE_OPTIONS } from '../../webpack-config'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { verifyRootLayout } from '../../../lib/verifyRootLayout' import { verifyRootLayout } from '../../../lib/verifyRootLayout'
import * as Log from '../../output/log' import * as Log from '../../output/log'
import { APP_DIR_ALIAS } from '../../../lib/constants' import { APP_DIR_ALIAS, WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants'
import { import {
createMetadataExportsCode, createMetadataExportsCode,
createStaticMetadataFromRoute, createStaticMetadataFromRoute,
METADATA_RESOURCE_QUERY,
} from './metadata/discover' } from './metadata/discover'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import { isAppRouteRoute } from '../../../lib/is-app-route-route' import { isAppRouteRoute } from '../../../lib/is-app-route-route'
...@@ -102,7 +101,7 @@ async function createAppRouteCode({ ...@@ -102,7 +101,7 @@ async function createAppRouteCode({
resolvedPagePath = `next-metadata-route-loader?${stringify({ resolvedPagePath = `next-metadata-route-loader?${stringify({
page, page,
pageExtensions, pageExtensions,
})}!${resolvedPagePath + METADATA_RESOURCE_QUERY}` })}!${resolvedPagePath + '?' + WEBPACK_RESOURCE_QUERIES.metadata}`
} }
// References the route handler file to load found in `./routes/${kind}.ts`. // References the route handler file to load found in `./routes/${kind}.ts`.
......
...@@ -2,6 +2,7 @@ import { getModuleBuildInfo } from '../get-module-build-info' ...@@ -2,6 +2,7 @@ import { getModuleBuildInfo } from '../get-module-build-info'
import { stringifyRequest } from '../../stringify-request' import { stringifyRequest } from '../../stringify-request'
import { NextConfig } from '../../../../server/config-shared' import { NextConfig } from '../../../../server/config-shared'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
export type EdgeAppRouteLoaderQuery = { export type EdgeAppRouteLoaderQuery = {
absolutePagePath: string absolutePagePath: string
...@@ -42,7 +43,9 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -42,7 +43,9 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
const modulePath = `${appDirLoader}${stringifiedPagePath.substring( const modulePath = `${appDirLoader}${stringifiedPagePath.substring(
1, 1,
stringifiedPagePath.length - 1 stringifiedPagePath.length - 1
)}?__edge_ssr_entry__` )}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}&${
WEBPACK_RESOURCE_QUERIES.metadata
}`
return ` return `
import { EdgeRouteModuleWrapper } from 'next/dist/esm/server/web/edge-route-module-wrapper' import { EdgeRouteModuleWrapper } from 'next/dist/esm/server/web/edge-route-module-wrapper'
......
import type webpack from 'webpack' import type webpack from 'webpack'
import { getModuleBuildInfo } from '../get-module-build-info' import { getModuleBuildInfo } from '../get-module-build-info'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
import { stringifyRequest } from '../../stringify-request' import { stringifyRequest } from '../../stringify-request'
export type EdgeSSRLoaderQuery = { export type EdgeSSRLoaderQuery = {
...@@ -91,7 +92,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -91,7 +92,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring( const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(
1, 1,
stringifiedPagePath.length - 1 stringifiedPagePath.length - 1
)}${isAppDir ? '?__edge_ssr_entry__' : ''}` )}${isAppDir ? `?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}` : ''}`
const transformed = ` const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
......
import type webpack from 'webpack' import type webpack from 'webpack'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import { METADATA_RESOURCE_QUERY } from './metadata/discover'
import { imageExtMimeTypeMap } from '../../../lib/mime-type' import { imageExtMimeTypeMap } from '../../../lib/mime-type'
import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants'
const cacheHeader = { const cacheHeader = {
none: 'no-cache, no-store', none: 'no-cache, no-store',
...@@ -51,7 +51,7 @@ const contentType = ${JSON.stringify(getContentType(resourcePath))} ...@@ -51,7 +51,7 @@ const contentType = ${JSON.stringify(getContentType(resourcePath))}
const buffer = Buffer.from(${JSON.stringify( const buffer = Buffer.from(${JSON.stringify(
( (
await fs.promises.readFile( await fs.promises.readFile(
resourcePath.replace(METADATA_RESOURCE_QUERY, '') resourcePath.replace('?' + WEBPACK_RESOURCE_QUERIES.metadata, '')
) )
).toString('base64') ).toString('base64')
)}, 'base64' )}, 'base64'
......
...@@ -96,3 +96,8 @@ export const WEBPACK_LAYERS = { ...@@ -96,3 +96,8 @@ export const WEBPACK_LAYERS = {
edgeAsset: 'edge-asset', edgeAsset: 'edge-asset',
appClient: 'app-client', appClient: 'app-client',
} }
export const WEBPACK_RESOURCE_QUERIES = {
edgeSSREntry: '__next_edge_ssr_entry__',
metadata: '__next_metadata__',
}
import { isMetadataRoute, isMetadataRouteFile } from './is-metadata-route' import { isMetadataRoute, isStaticMetadataRouteFile } 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'
...@@ -74,7 +74,7 @@ export function normalizeMetadataRoute(page: string) { ...@@ -74,7 +74,7 @@ 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(page, [], true) const isStaticMetadataFile = isStaticMetadataRouteFile(page)
const { dir, name: baseName, ext } = path.parse(route) const { dir, name: baseName, ext } = path.parse(route)
const isStaticRoute = const isStaticRoute =
......
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
export const STATIC_METADATA_IMAGES = { export const STATIC_METADATA_IMAGES = {
icon: { icon: {
filename: 'icon', filename: 'icon',
...@@ -102,7 +104,14 @@ export function isMetadataRouteFile( ...@@ -102,7 +104,14 @@ export function isMetadataRouteFile(
), ),
] ]
return metadataRouteFilesRegex.some((r) => r.test(appDirRelativePath)) const normalizedAppDirRelativePath = normalizePathSep(appDirRelativePath)
return metadataRouteFilesRegex.some((r) =>
r.test(normalizedAppDirRelativePath)
)
}
export function isStaticMetadataRouteFile(appDirRelativePath: string) {
return isMetadataRouteFile(appDirRelativePath, [], true)
} }
/* /*
......
export default function layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const runtime = 'experimental-edge'
export default function page() {
return <div>hello edge</div>
}
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'app-dir edge runtime root layout',
{
files: __dirname,
skipDeployment: true,
},
({ next, isNextStart }) => {
it('should not emit metadata files into bad paths', async () => {
await next.fetch('/favicon.ico')
// issue: If metadata files are not filter out properly with image-loader,
// an incorrect static/media folder will be generated
// Check that the static folder is not generated
const incorrectGeneratedStaticFolder = await next.hasFile('static')
expect(incorrectGeneratedStaticFolder).toBe(false)
})
if (isNextStart) {
it('should mark static contain metadata routes as edge functions', async () => {
const middlewareManifest = await next.readFile(
'.next/server/middleware-manifest.json'
)
expect(middlewareManifest).not.toContain('favicon')
})
}
}
)
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