Unverified Commit 7c969652 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Include nextConfig in edge runtime via separate manifest (#86769)

A separate manifest (`required-server-files.js`, like `_buildManifest.js`) so that we the bundler doesn't have to inline the whole config.

The Node.js runtime routes already get their nextConfig at runtime by reading `required-server-files.js`.

Closes https://github.com/vercel/next.js/pull/86630

Context for `initializeCacheHandlers`: https://github.com/vercel/next.js/pull/76130
parent 7fed4e52
...@@ -1543,6 +1543,9 @@ impl AppEndpoint { ...@@ -1543,6 +1543,9 @@ impl AppEndpoint {
rcstr!("server/middleware-build-manifest.js"), rcstr!("server/middleware-build-manifest.js"),
rcstr!("server/interception-route-rewrite-manifest.js"), rcstr!("server/interception-route-rewrite-manifest.js"),
]; ];
if project.next_mode().await?.is_production() {
file_paths_from_root.insert(rcstr!("required-server-files.js"));
}
if emit_manifests == EmitManifests::Full { if emit_manifests == EmitManifests::Full {
file_paths_from_root.insert(rcstr!("server/next-font-manifest.js")); file_paths_from_root.insert(rcstr!("server/next-font-manifest.js"));
}; };
......
...@@ -904,7 +904,6 @@ impl PageEndpoint { ...@@ -904,7 +904,6 @@ impl PageEndpoint {
this.original_name.clone(), this.original_name.clone(),
*this.pages_structure, *this.pages_structure,
runtime, runtime,
this.pages_project.project().next_config(),
) )
.await?; .await?;
...@@ -1441,6 +1440,16 @@ impl PageEndpoint { ...@@ -1441,6 +1440,16 @@ impl PageEndpoint {
fxindexset![] fxindexset![]
}; };
if this
.pages_project
.project()
.next_mode()
.await?
.is_production()
{
file_paths_from_root.insert(rcstr!("required-server-files.js"));
}
let all_assets = assets.concatenate(*referenced_assets); let all_assets = assets.concatenate(*referenced_assets);
let assets_ref = assets.await?; let assets_ref = assets.await?;
......
...@@ -122,7 +122,6 @@ pub async fn get_app_page_entry( ...@@ -122,7 +122,6 @@ pub async fn get_app_page_entry(
project_root.clone(), project_root.clone(),
rsc_entry, rsc_entry,
page, page,
next_config,
); );
}; };
...@@ -141,21 +140,14 @@ async fn wrap_edge_page( ...@@ -141,21 +140,14 @@ async fn wrap_edge_page(
project_root: FileSystemPath, project_root: FileSystemPath,
entry: ResolvedVc<Box<dyn Module>>, entry: ResolvedVc<Box<dyn Module>>,
page: AppPage, page: AppPage,
next_config: Vc<NextConfig>,
) -> Result<Vc<Box<dyn Module>>> { ) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_PAGE_ENTRY"; const INNER: &str = "INNER_PAGE_ENTRY";
let next_config_val = &*next_config.await?;
let source = load_next_js_template( let source = load_next_js_template(
"edge-ssr-app.js", "edge-ssr-app.js",
project_root.clone(), project_root.clone(),
[("VAR_USERLAND", INNER), ("VAR_PAGE", &page.to_string())], [("VAR_USERLAND", INNER), ("VAR_PAGE", &page.to_string())],
[ [],
// TODO do we really need to pass the entire next config here?
// This is bad for invalidation as any config change will invalidate this
("nextConfig", &*serde_json::to_string(next_config_val)?),
],
[("incrementalCacheHandler", None)], [("incrementalCacheHandler", None)],
) )
.await?; .await?;
......
...@@ -113,7 +113,6 @@ pub async fn get_app_route_entry( ...@@ -113,7 +113,6 @@ pub async fn get_app_route_entry(
project_root, project_root,
rsc_entry, rsc_entry,
page, page,
next_config,
); );
} }
...@@ -132,17 +131,14 @@ async fn wrap_edge_route( ...@@ -132,17 +131,14 @@ async fn wrap_edge_route(
project_root: FileSystemPath, project_root: FileSystemPath,
entry: ResolvedVc<Box<dyn Module>>, entry: ResolvedVc<Box<dyn Module>>,
page: AppPage, page: AppPage,
next_config: Vc<NextConfig>,
) -> Result<Vc<Box<dyn Module>>> { ) -> Result<Vc<Box<dyn Module>>> {
let inner = rcstr!("INNER_ROUTE_ENTRY"); let inner = rcstr!("INNER_ROUTE_ENTRY");
let next_config = &*next_config.await?;
let source = load_next_js_template( let source = load_next_js_template(
"edge-app-route.js", "edge-app-route.js",
project_root.clone(), project_root.clone(),
[("VAR_USERLAND", &*inner), ("VAR_PAGE", &page.to_string())], [("VAR_USERLAND", &*inner), ("VAR_PAGE", &page.to_string())],
[("nextConfig", &*serde_json::to_string(next_config)?)], [],
[], [],
) )
.await?; .await?;
......
...@@ -16,7 +16,6 @@ use turbopack_core::{ ...@@ -16,7 +16,6 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
next_config::NextConfig,
next_edge::entry::wrap_edge_entry, next_edge::entry::wrap_edge_entry,
pages_structure::{PagesStructure, PagesStructureItem}, pages_structure::{PagesStructure, PagesStructureItem},
util::{NextRuntime, file_content_rope, load_next_js_template, pages_function_name}, util::{NextRuntime, file_content_rope, load_next_js_template, pages_function_name},
...@@ -39,7 +38,6 @@ pub async fn create_page_ssr_entry_module( ...@@ -39,7 +38,6 @@ pub async fn create_page_ssr_entry_module(
next_original_name: RcStr, next_original_name: RcStr,
pages_structure: Vc<PagesStructure>, pages_structure: Vc<PagesStructure>,
runtime: NextRuntime, runtime: NextRuntime,
next_config: Vc<NextConfig>,
) -> Result<Vc<PageSsrEntryModule>> { ) -> Result<Vc<PageSsrEntryModule>> {
let definition_page = next_original_name; let definition_page = next_original_name;
let definition_pathname = pathname; let definition_pathname = pathname;
...@@ -99,11 +97,7 @@ pub async fn create_page_ssr_entry_module( ...@@ -99,11 +97,7 @@ pub async fn create_page_ssr_entry_module(
let pages_structure_ref = pages_structure.await?; let pages_structure_ref = pages_structure.await?;
let (injections, imports) = if is_page && runtime == NextRuntime::Edge { let (injections, imports) = if is_page && runtime == NextRuntime::Edge {
let next_config_val = &*next_config.await?;
let injections = vec![ let injections = vec![
// TODO do we really need to pass the entire next config here?
// This is bad for invalidation as any config change will invalidate this
("nextConfig", serde_json::to_string(next_config_val)?),
( (
"pageRouteModuleOptions", "pageRouteModuleOptions",
serde_json::to_string(&get_route_module_options( serde_json::to_string(&get_route_module_options(
......
...@@ -965,5 +965,7 @@ ...@@ -965,5 +965,7 @@
"964": "An unexpected error occurred while starting to capture immediates", "964": "An unexpected error occurred while starting to capture immediates",
"965": "Expected setImmediate to reject invalid arguments", "965": "Expected setImmediate to reject invalid arguments",
"966": "Expected process.nextTick to reject invalid arguments", "966": "Expected process.nextTick to reject invalid arguments",
"967": "The key \"%s\" under \"env\" in %sconfig is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed" "967": "The key \"%s\" under \"env\" in %sconfig is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed",
"968": "Invariant: getNextConfigEdge must only be called in edge runtime",
"969": "Invariant: nextConfig couldn't be loaded"
} }
...@@ -296,7 +296,7 @@ export function getDefineEnv({ ...@@ -296,7 +296,7 @@ export function getDefineEnv({
config.experimental.trustHostHeader ?? false, config.experimental.trustHostHeader ?? false,
'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS': 'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS':
config.experimental.allowedRevalidateHeaderKeys ?? [], config.experimental.allowedRevalidateHeaderKeys ?? [],
...(isNodeServer ...(isNodeServer || isEdgeServer
? { ? {
'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir, 'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir,
'process.env.__NEXT_RELATIVE_PROJECT_DIR': path.relative( 'process.env.__NEXT_RELATIVE_PROJECT_DIR': path.relative(
......
...@@ -621,7 +621,6 @@ export function getEdgeServerEntry(opts: { ...@@ -621,7 +621,6 @@ export function getEdgeServerEntry(opts: {
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
page: opts.page, page: opts.page,
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'), appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
nextConfig: Buffer.from(JSON.stringify(opts.config)).toString('base64'),
preferredRegion: opts.preferredRegion, preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from( middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {}) JSON.stringify(opts.middlewareConfig || {})
...@@ -682,9 +681,6 @@ export function getEdgeServerEntry(opts: { ...@@ -682,9 +681,6 @@ export function getEdgeServerEntry(opts: {
dev: opts.isDev, dev: opts.isDev,
isServerComponent: opts.isServerComponent, isServerComponent: opts.isServerComponent,
page: opts.page, page: opts.page,
stringifiedConfig: Buffer.from(JSON.stringify(opts.config)).toString(
'base64'
),
pagesType: opts.pagesType, pagesType: opts.pagesType,
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'), appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm, sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm,
......
...@@ -621,9 +621,13 @@ async function writeRequiredServerFilesManifest( ...@@ -621,9 +621,13 @@ async function writeRequiredServerFilesManifest(
requiredServerFiles: RequiredServerFilesManifest requiredServerFiles: RequiredServerFilesManifest
) { ) {
await writeManifest( await writeManifest(
path.join(distDir, SERVER_FILES_MANIFEST), path.join(distDir, SERVER_FILES_MANIFEST + '.json'),
requiredServerFiles requiredServerFiles
) )
await writeFileUtf8(
path.join(distDir, SERVER_FILES_MANIFEST + '.js'),
`self.__SERVER_FILES_MANIFEST=${formatManifest(requiredServerFiles)}`
)
} }
async function writeImagesManifest( async function writeImagesManifest(
...@@ -693,7 +697,10 @@ async function writeStandaloneDirectory( ...@@ -693,7 +697,10 @@ async function writeStandaloneDirectory(
for (const file of [ for (const file of [
...requiredServerFiles.files, ...requiredServerFiles.files,
path.join(requiredServerFiles.config.distDir, SERVER_FILES_MANIFEST), path.join(
requiredServerFiles.config.distDir,
SERVER_FILES_MANIFEST + '.json'
),
...loadedEnvFiles.reduce<string[]>((acc, envFile) => { ...loadedEnvFiles.reduce<string[]>((acc, envFile) => {
if (['.env', '.env.production'].includes(envFile.path)) { if (['.env', '.env.production'].includes(envFile.path)) {
acc.push(envFile.path) acc.push(envFile.path)
...@@ -1915,7 +1922,7 @@ export default async function build( ...@@ -1915,7 +1922,7 @@ export default async function build(
BUILD_ID_FILE, BUILD_ID_FILE,
path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.js'), path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.js'),
path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.json'), path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.json'),
SERVER_FILES_MANIFEST, SERVER_FILES_MANIFEST + '.json',
] ]
.filter(nonNullable) .filter(nonNullable)
.map((file) => path.join(config.distDir, file)), .map((file) => path.join(config.distDir, file)),
......
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import type { NextConfigRuntime } from '../../server/config-shared'
import type { EdgeHandler } from '../../server/web/adapter' import type { EdgeHandler } from '../../server/web/adapter'
import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper' import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper'
...@@ -7,8 +6,6 @@ import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapp ...@@ -7,8 +6,6 @@ import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapp
import * as module from 'VAR_USERLAND' import * as module from 'VAR_USERLAND'
// injected by the loader afterwards. // injected by the loader afterwards.
declare const nextConfig: NextConfigRuntime
// INJECT:nextConfig
const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined) const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)
...@@ -26,7 +23,6 @@ if (rscManifest && rscServerManifest) { ...@@ -26,7 +23,6 @@ if (rscManifest && rscServerManifest) {
export const ComponentMod = module export const ComponentMod = module
const handler: EdgeHandler = EdgeRouteModuleWrapper.wrap(module.routeModule, { const handler: EdgeHandler = EdgeRouteModuleWrapper.wrap(module.routeModule, {
nextConfig,
page: 'VAR_PAGE', page: 'VAR_PAGE',
}) })
export default handler export default handler
...@@ -8,7 +8,6 @@ import { IncrementalCache } from '../../server/lib/incremental-cache' ...@@ -8,7 +8,6 @@ import { IncrementalCache } from '../../server/lib/incremental-cache'
import * as pageMod from 'VAR_USERLAND' import * as pageMod from 'VAR_USERLAND'
import type { NextConfigRuntime } from '../../server/config-shared'
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { initializeCacheHandlers } from '../../server/use-cache/handlers' import { initializeCacheHandlers } from '../../server/use-cache/handlers'
import { BaseServerSpan } from '../../server/lib/trace/constants' import { BaseServerSpan } from '../../server/lib/trace/constants'
...@@ -29,12 +28,7 @@ import { checkIsOnDemandRevalidate } from '../../server/api-utils' ...@@ -29,12 +28,7 @@ import { checkIsOnDemandRevalidate } from '../../server/api-utils'
import { CloseController } from '../../server/web/web-on-close' import { CloseController } from '../../server/web/web-on-close'
declare const incrementalCacheHandler: any declare const incrementalCacheHandler: any
declare const nextConfig: NextConfigRuntime
// OPTIONAL_IMPORT:incrementalCacheHandler // OPTIONAL_IMPORT:incrementalCacheHandler
// INJECT:nextConfig
// Initialize the cache handlers interface.
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)
const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined) const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)
...@@ -77,6 +71,7 @@ async function requestHandler( ...@@ -77,6 +71,7 @@ async function requestHandler(
query, query,
params, params,
buildId, buildId,
nextConfig,
buildManifest, buildManifest,
prerenderManifest, prerenderManifest,
reactLoadableManifest, reactLoadableManifest,
...@@ -88,6 +83,9 @@ async function requestHandler( ...@@ -88,6 +83,9 @@ async function requestHandler(
routerServerContext, routerServerContext,
} = prepareResult } = prepareResult
// Initialize the cache handlers interface.
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)
const isPossibleServerAction = getIsPossibleServerAction(req) const isPossibleServerAction = getIsPossibleServerAction(req)
const botType = getBotType(req.headers.get('User-Agent') || '') const botType = getBotType(req.headers.get('User-Agent') || '')
const { isOnDemandRevalidate } = checkIsOnDemandRevalidate( const { isOnDemandRevalidate } = checkIsOnDemandRevalidate(
......
...@@ -22,7 +22,6 @@ import RouteModule, { ...@@ -22,7 +22,6 @@ import RouteModule, {
} from '../../server/route-modules/pages/module' } from '../../server/route-modules/pages/module'
import { WebNextRequest, WebNextResponse } from '../../server/base-http/web' import { WebNextRequest, WebNextResponse } from '../../server/base-http/web'
import type { NextConfigRuntime } from '../../server/config-shared'
import type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event' import type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event'
import type RenderResult from '../../server/render-result' import type RenderResult from '../../server/render-result'
import type { RenderResultMetadata } from '../../server/render-result' import type { RenderResultMetadata } from '../../server/render-result'
...@@ -31,21 +30,13 @@ import { BaseServerSpan } from '../../server/lib/trace/constants' ...@@ -31,21 +30,13 @@ import { BaseServerSpan } from '../../server/lib/trace/constants'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants' import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
// injected by the loader afterwards. // injected by the loader afterwards.
declare const nextConfig: NextConfigRuntime
declare const pageRouteModuleOptions: any declare const pageRouteModuleOptions: any
declare const errorRouteModuleOptions: any declare const errorRouteModuleOptions: any
declare const user500RouteModuleOptions: any declare const user500RouteModuleOptions: any
// INJECT:nextConfig
// INJECT:pageRouteModuleOptions // INJECT:pageRouteModuleOptions
// INJECT:errorRouteModuleOptions // INJECT:errorRouteModuleOptions
// INJECT:user500RouteModuleOptions // INJECT:user500RouteModuleOptions
// Initialize the cache handlers interface.
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)
// expose this for the route-module
;(globalThis as any).nextConfig = nextConfig
const pageMod = { const pageMod = {
...userlandPage, ...userlandPage,
routeModule: new RouteModule({ routeModule: new RouteModule({
...@@ -55,6 +46,8 @@ const pageMod = { ...@@ -55,6 +46,8 @@ const pageMod = {
Document, Document,
}, },
userland: userlandPage, userland: userlandPage,
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
}), }),
} }
...@@ -67,6 +60,8 @@ const errorMod = { ...@@ -67,6 +60,8 @@ const errorMod = {
Document, Document,
}, },
userland: userlandErrorPage, userland: userlandErrorPage,
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
}), }),
} }
...@@ -81,6 +76,8 @@ const error500Mod = userland500Page ...@@ -81,6 +76,8 @@ const error500Mod = userland500Page
Document, Document,
}, },
userland: userland500Page, userland: userland500Page,
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
}), }),
} }
: null : null
...@@ -110,6 +107,7 @@ async function requestHandler( ...@@ -110,6 +107,7 @@ async function requestHandler(
query, query,
params, params,
buildId, buildId,
nextConfig,
isNextDataRequest, isNextDataRequest,
buildManifest, buildManifest,
prerenderManifest, prerenderManifest,
...@@ -119,6 +117,8 @@ async function requestHandler( ...@@ -119,6 +117,8 @@ async function requestHandler(
dynamicCssManifest, dynamicCssManifest,
} = prepareResult } = prepareResult
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)
const renderContext: PagesRouteHandlerContext = { const renderContext: PagesRouteHandlerContext = {
page: srcPage, page: srcPage,
query, query,
......
...@@ -11,7 +11,6 @@ export type EdgeAppRouteLoaderQuery = { ...@@ -11,7 +11,6 @@ export type EdgeAppRouteLoaderQuery = {
page: string page: string
appDirLoader: string appDirLoader: string
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
nextConfig: string
middlewareConfig: string middlewareConfig: string
cacheHandlers: string cacheHandlers: string
} }
...@@ -24,7 +23,6 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -24,7 +23,6 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
preferredRegion, preferredRegion,
appDirLoader: appDirLoaderBase64 = '', appDirLoader: appDirLoaderBase64 = '',
middlewareConfig: middlewareConfigBase64 = '', middlewareConfig: middlewareConfigBase64 = '',
nextConfig: nextConfigBase64,
cacheHandlers: cacheHandlersStringified, cacheHandlers: cacheHandlersStringified,
} = this.getOptions() } = this.getOptions()
...@@ -64,20 +62,13 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -64,20 +62,13 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
stringifiedPagePath.length - 1 stringifiedPagePath.length - 1
)}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}` )}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}`
const stringifiedConfig = Buffer.from(
nextConfigBase64 || '',
'base64'
).toString()
return await loadEntrypoint( return await loadEntrypoint(
'edge-app-route', 'edge-app-route',
{ {
VAR_USERLAND: modulePath, VAR_USERLAND: modulePath,
VAR_PAGE: page, VAR_PAGE: page,
}, },
{ {}
nextConfig: stringifiedConfig,
}
) )
} }
......
...@@ -19,7 +19,6 @@ export type EdgeSSRLoaderQuery = { ...@@ -19,7 +19,6 @@ export type EdgeSSRLoaderQuery = {
dev: boolean dev: boolean
isServerComponent: boolean isServerComponent: boolean
page: string page: string
stringifiedConfig: string
appDirLoader?: string appDirLoader?: string
pagesType: PAGE_TYPES pagesType: PAGE_TYPES
sriEnabled: boolean sriEnabled: boolean
...@@ -46,7 +45,10 @@ function swapDistFolderWithEsmDistFolder(path: string) { ...@@ -46,7 +45,10 @@ function swapDistFolderWithEsmDistFolder(path: string) {
} }
function getRouteModuleOptions(page: string) { function getRouteModuleOptions(page: string) {
const options: Omit<PagesRouteModuleOptions, 'userland' | 'components'> = { const options: Omit<
PagesRouteModuleOptions,
'userland' | 'components' | 'distDir' | 'relativeProjectDir'
> = {
definition: { definition: {
kind: RouteKind.PAGES, kind: RouteKind.PAGES,
page: normalizePagePath(page), page: normalizePagePath(page),
...@@ -55,9 +57,6 @@ function getRouteModuleOptions(page: string) { ...@@ -55,9 +57,6 @@ function getRouteModuleOptions(page: string) {
bundlePath: '', bundlePath: '',
filename: '', filename: '',
}, },
// edge runtime doesn't read from distDir or projectDir
distDir: '',
relativeProjectDir: '',
} }
return options return options
...@@ -73,7 +72,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -73,7 +72,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
absolute500Path, absolute500Path,
absoluteErrorPath, absoluteErrorPath,
isServerComponent, isServerComponent,
stringifiedConfig: stringifiedConfigBase64,
appDirLoader: appDirLoaderBase64, appDirLoader: appDirLoaderBase64,
pagesType, pagesType,
cacheHandler, cacheHandler,
...@@ -94,10 +92,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -94,10 +92,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
) )
const stringifiedConfig = Buffer.from(
stringifiedConfigBase64 || '',
'base64'
).toString()
const appDirLoader = Buffer.from( const appDirLoader = Buffer.from(
appDirLoaderBase64 || '', appDirLoaderBase64 || '',
'base64' 'base64'
...@@ -160,9 +154,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -160,9 +154,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
VAR_USERLAND: pageModPath, VAR_USERLAND: pageModPath,
VAR_PAGE: page, VAR_PAGE: page,
}, },
{ {},
nextConfig: stringifiedConfig,
},
{ {
incrementalCacheHandler: cacheHandler ?? null, incrementalCacheHandler: cacheHandler ?? null,
} }
...@@ -178,7 +170,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -178,7 +170,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
VAR_MODULE_GLOBAL_ERROR: errorPath, VAR_MODULE_GLOBAL_ERROR: errorPath,
}, },
{ {
nextConfig: stringifiedConfig,
pageRouteModuleOptions: JSON.stringify(getRouteModuleOptions(page)), pageRouteModuleOptions: JSON.stringify(getRouteModuleOptions(page)),
errorRouteModuleOptions: JSON.stringify( errorRouteModuleOptions: JSON.stringify(
getRouteModuleOptions('/_error') getRouteModuleOptions('/_error')
......
...@@ -22,6 +22,7 @@ import { ...@@ -22,6 +22,7 @@ import {
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
INTERCEPTION_ROUTE_REWRITE_MANIFEST, INTERCEPTION_ROUTE_REWRITE_MANIFEST,
DYNAMIC_CSS_MANIFEST, DYNAMIC_CSS_MANIFEST,
SERVER_FILES_MANIFEST,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import type { ProxyConfig } from '../../analysis/get-page-static-info' import type { ProxyConfig } from '../../analysis/get-page-static-info'
import type { Telemetry } from '../../../telemetry/storage' import type { Telemetry } from '../../../telemetry/storage'
...@@ -133,6 +134,10 @@ function getEntryFiles( ...@@ -133,6 +134,10 @@ function getEntryFiles(
`server/${NEXT_FONT_MANIFEST}.js`, `server/${NEXT_FONT_MANIFEST}.js`,
`server/${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js` `server/${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`
) )
if (!opts.dev) {
files.push(`${SERVER_FILES_MANIFEST}.js`)
}
} }
if (hasInstrumentationHook) { if (hasInstrumentationHook) {
......
import type { ComponentType } from 'react' import type { ComponentType } from 'react'
import type { ProxyMatcher } from '../build/analysis/get-page-static-info' import type { ProxyMatcher } from '../build/analysis/get-page-static-info'
import type { RequiredServerFilesManifest } from '../build'
import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route' import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route'
import { __unsafeCreateTrustedScriptURL } from './trusted-types' import { __unsafeCreateTrustedScriptURL } from './trusted-types'
import { requestIdleCallback } from './request-idle-callback' import { requestIdleCallback } from './request-idle-callback'
...@@ -16,6 +17,7 @@ declare global { ...@@ -16,6 +17,7 @@ declare global {
interface Window { interface Window {
__BUILD_MANIFEST?: Record<string, string[]> __BUILD_MANIFEST?: Record<string, string[]>
__BUILD_MANIFEST_CB?: Function __BUILD_MANIFEST_CB?: Function
__SERVER_FILES_MANIFEST?: RequiredServerFilesManifest
__MIDDLEWARE_MATCHERS?: ProxyMatcher[] __MIDDLEWARE_MATCHERS?: ProxyMatcher[]
__MIDDLEWARE_MANIFEST_CB?: Function __MIDDLEWARE_MANIFEST_CB?: Function
__REACT_LOADABLE_MANIFEST?: any __REACT_LOADABLE_MANIFEST?: any
......
...@@ -298,7 +298,7 @@ export class NextServer implements NextWrapperServer { ...@@ -298,7 +298,7 @@ export class NextServer implements NextWrapperServer {
path.join( path.join(
/* turbopackIgnore: true */ dir, /* turbopackIgnore: true */ dir,
config.distDir, config.distDir,
SERVER_FILES_MANIFEST SERVER_FILES_MANIFEST + '.json'
) )
).config ).config
......
...@@ -42,7 +42,11 @@ import type { ReactLoadableManifest } from '../load-components' ...@@ -42,7 +42,11 @@ import type { ReactLoadableManifest } from '../load-components'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import { normalizeDataPath } from '../../shared/lib/page-path/normalize-data-path' import { normalizeDataPath } from '../../shared/lib/page-path/normalize-data-path'
import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'
import { addRequestMeta, getRequestMeta } from '../request-meta' import {
addRequestMeta,
getRequestMeta,
type NextIncomingMessage,
} from '../request-meta'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { isStaticMetadataRoute } from '../../lib/metadata/is-metadata-route' import { isStaticMetadataRoute } from '../../lib/metadata/is-metadata-route'
import { IncrementalCache } from '../lib/incremental-cache' import { IncrementalCache } from '../lib/incremental-cache'
...@@ -178,7 +182,7 @@ export abstract class RouteModule< ...@@ -178,7 +182,7 @@ export abstract class RouteModule<
routesManifest: DeepReadonly<DevRoutesManifest> routesManifest: DeepReadonly<DevRoutesManifest>
nextFontManifest: DeepReadonly<NextFontManifest> nextFontManifest: DeepReadonly<NextFontManifest>
prerenderManifest: DeepReadonly<PrerenderManifest> prerenderManifest: DeepReadonly<PrerenderManifest>
serverFilesManifest: RequiredServerFilesManifest serverFilesManifest: RequiredServerFilesManifest | undefined
reactLoadableManifest: DeepReadonly<ReactLoadableManifest> reactLoadableManifest: DeepReadonly<ReactLoadableManifest>
subresourceIntegrityManifest: any subresourceIntegrityManifest: any
clientReferenceManifest: any clientReferenceManifest: any
...@@ -223,9 +227,7 @@ export abstract class RouteModule< ...@@ -223,9 +227,7 @@ export abstract class RouteModule<
process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE
), ),
}, },
serverFilesManifest: { serverFilesManifest: self.__SERVER_FILES_MANIFEST,
config: (globalThis as any).nextConfig || {},
} as any,
clientReferenceManifest: self.__RSC_MANIFEST?.[srcPage], clientReferenceManifest: self.__RSC_MANIFEST?.[srcPage],
serverActionsManifest: maybeJSONParse(self.__RSC_SERVER_MANIFEST), serverActionsManifest: maybeJSONParse(self.__RSC_SERVER_MANIFEST),
subresourceIntegrityManifest: maybeJSONParse( subresourceIntegrityManifest: maybeJSONParse(
...@@ -333,12 +335,12 @@ export abstract class RouteModule< ...@@ -333,12 +335,12 @@ export abstract class RouteModule<
shouldCache: !this.isDev, shouldCache: !this.isDev,
}), }),
this.isDev this.isDev
? ({} as any) ? undefined
: loadManifestFromRelativePath<RequiredServerFilesManifest>({ : (loadManifestFromRelativePath<RequiredServerFilesManifest>({
projectDir, projectDir,
distDir: this.distDir, distDir: this.distDir,
manifest: SERVER_FILES_MANIFEST, manifest: `${SERVER_FILES_MANIFEST}.json`,
}), }) as RequiredServerFilesManifest),
this.isDev this.isDev
? 'development' ? 'development'
: loadManifestFromRelativePath<any>({ : loadManifestFromRelativePath<any>({
...@@ -500,6 +502,31 @@ export abstract class RouteModule< ...@@ -500,6 +502,31 @@ export abstract class RouteModule<
) )
} }
/** A more lightweight version of `prepare()` for only retrieving the config on edge */
public getNextConfigEdge(req: NextIncomingMessage): NextConfigRuntime {
if (process.env.NEXT_RUNTIME !== 'edge') {
throw new Error(
'Invariant: getNextConfigEdge must only be called in edge runtime'
)
}
let serverFilesManifest = self.__SERVER_FILES_MANIFEST as any as
| RequiredServerFilesManifest
| undefined
const relativeProjectDir =
getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir
const routerServerContext =
routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]
const nextConfig =
routerServerContext?.nextConfig || serverFilesManifest?.config
if (!nextConfig) {
throw new Error("Invariant: nextConfig couldn't be loaded")
}
return nextConfig
}
public async prepare( public async prepare(
req: IncomingMessage | BaseNextRequest, req: IncomingMessage | BaseNextRequest,
res: ServerResponse | null, res: ServerResponse | null,
...@@ -530,7 +557,9 @@ export abstract class RouteModule< ...@@ -530,7 +557,9 @@ export abstract class RouteModule<
buildManifest: DeepReadonly<BuildManifest> buildManifest: DeepReadonly<BuildManifest>
fallbackBuildManifest: DeepReadonly<BuildManifest> fallbackBuildManifest: DeepReadonly<BuildManifest>
nextFontManifest: DeepReadonly<NextFontManifest> nextFontManifest: DeepReadonly<NextFontManifest>
serverFilesManifest: DeepReadonly<RequiredServerFilesManifest> serverFilesManifest:
| DeepReadonly<RequiredServerFilesManifest>
| undefined
reactLoadableManifest: DeepReadonly<ReactLoadableManifest> reactLoadableManifest: DeepReadonly<ReactLoadableManifest>
routesManifest: DeepReadonly<DevRoutesManifest> routesManifest: DeepReadonly<DevRoutesManifest>
prerenderManifest: DeepReadonly<PrerenderManifest> prerenderManifest: DeepReadonly<PrerenderManifest>
...@@ -849,7 +878,11 @@ export abstract class RouteModule< ...@@ -849,7 +878,11 @@ export abstract class RouteModule<
const routerServerContext = const routerServerContext =
routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir] routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]
const nextConfig = const nextConfig =
routerServerContext?.nextConfig || serverFilesManifest.config routerServerContext?.nextConfig || serverFilesManifest?.config
if (!nextConfig) {
throw new Error("Invariant: nextConfig couldn't be loaded")
}
let resolvedPathname = normalizedSrcPage let resolvedPathname = normalizedSrcPage
if (isDynamicRoute(resolvedPathname) && params) { if (isDynamicRoute(resolvedPathname) && params) {
...@@ -890,7 +923,6 @@ export abstract class RouteModule< ...@@ -890,7 +923,6 @@ export abstract class RouteModule<
isOnDemandRevalidate, isOnDemandRevalidate,
revalidateOnlyGenerated, revalidateOnlyGenerated,
...manifests, ...manifests,
serverActionsManifest: manifests.serverActionsManifest,
clientReferenceManifest: manifests.clientReferenceManifest, clientReferenceManifest: manifests.clientReferenceManifest,
nextConfig, nextConfig,
routerServerContext, routerServerContext,
......
import type { NextRequest } from './spec-extension/request'
import type { import type {
AppRouteRouteHandlerContext, AppRouteRouteHandlerContext,
AppRouteRouteModule, AppRouteRouteModule,
...@@ -6,7 +5,7 @@ import type { ...@@ -6,7 +5,7 @@ import type {
import './globals' import './globals'
import { adapter, type EdgeHandler } from './adapter' import { adapter, type NextRequestHint, type EdgeHandler } from './adapter'
import { IncrementalCache } from '../lib/incremental-cache' import { IncrementalCache } from '../lib/incremental-cache'
import { RouteMatcher } from '../route-matchers/route-matcher' import { RouteMatcher } from '../route-matchers/route-matcher'
import type { NextFetchEvent } from './spec-extension/fetch-event' import type { NextFetchEvent } from './spec-extension/fetch-event'
...@@ -15,10 +14,9 @@ import { getServerUtils } from '../server-utils' ...@@ -15,10 +14,9 @@ import { getServerUtils } from '../server-utils'
import { searchParamsToUrlQuery } from '../../shared/lib/router/utils/querystring' import { searchParamsToUrlQuery } from '../../shared/lib/router/utils/querystring'
import { CloseController, trackStreamConsumed } from './web-on-close' import { CloseController, trackStreamConsumed } from './web-on-close'
import { getEdgePreviewProps } from './get-edge-preview-props' import { getEdgePreviewProps } from './get-edge-preview-props'
import type { NextConfigRuntime } from '../config-shared' import { WebNextRequest } from '../../server/base-http/web'
export interface WrapOptions { export interface WrapOptions {
nextConfig: NextConfigRuntime
page: string page: string
} }
...@@ -36,10 +34,7 @@ export class EdgeRouteModuleWrapper { ...@@ -36,10 +34,7 @@ export class EdgeRouteModuleWrapper {
* *
* @param routeModule the route module to wrap * @param routeModule the route module to wrap
*/ */
private constructor( private constructor(private readonly routeModule: AppRouteRouteModule) {
private readonly routeModule: AppRouteRouteModule,
private readonly nextConfig: NextConfigRuntime
) {
// TODO: (wyattjoh) possibly allow the module to define it's own matcher // TODO: (wyattjoh) possibly allow the module to define it's own matcher
this.matcher = new RouteMatcher(routeModule.definition) this.matcher = new RouteMatcher(routeModule.definition)
} }
...@@ -58,7 +53,7 @@ export class EdgeRouteModuleWrapper { ...@@ -58,7 +53,7 @@ export class EdgeRouteModuleWrapper {
options: WrapOptions options: WrapOptions
): EdgeHandler { ): EdgeHandler {
// Create the module wrapper. // Create the module wrapper.
const wrapper = new EdgeRouteModuleWrapper(routeModule, options.nextConfig) const wrapper = new EdgeRouteModuleWrapper(routeModule)
// Return the wrapping function. // Return the wrapping function.
return (opts) => { return (opts) => {
...@@ -73,7 +68,7 @@ export class EdgeRouteModuleWrapper { ...@@ -73,7 +68,7 @@ export class EdgeRouteModuleWrapper {
} }
private async handler( private async handler(
request: NextRequest, request: NextRequestHint,
evt: NextFetchEvent evt: NextFetchEvent
): Promise<Response> { ): Promise<Response> {
const utils = getServerUtils({ const utils = getServerUtils({
...@@ -86,6 +81,10 @@ export class EdgeRouteModuleWrapper { ...@@ -86,6 +81,10 @@ export class EdgeRouteModuleWrapper {
caseSensitive: false, caseSensitive: false,
}) })
const nextConfig = this.routeModule.getNextConfigEdge(
new WebNextRequest(request)
)
const { params } = utils.normalizeDynamicRouteParams( const { params } = utils.normalizeDynamicRouteParams(
searchParamsToUrlQuery(request.nextUrl.searchParams), searchParamsToUrlQuery(request.nextUrl.searchParams),
false false
...@@ -116,7 +115,7 @@ export class EdgeRouteModuleWrapper { ...@@ -116,7 +115,7 @@ export class EdgeRouteModuleWrapper {
experimental: { experimental: {
authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS, authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS,
}, },
cacheLifeProfiles: this.nextConfig.cacheLife, cacheLifeProfiles: nextConfig.cacheLife,
}, },
sharedContext: { sharedContext: {
buildId: '', // TODO: Populate this properly. buildId: '', // TODO: Populate this properly.
......
...@@ -118,12 +118,11 @@ async function loadWasm( ...@@ -118,12 +118,11 @@ async function loadWasm(
function buildEnvironmentVariablesFrom( function buildEnvironmentVariablesFrom(
injectedEnvironments: Record<string, string> injectedEnvironments: Record<string, string>
): Record<string, string | undefined> { ): Record<string, string | undefined> {
const pairs = Object.keys(process.env).map((key) => [key, process.env[key]]) let env = Object.fromEntries([
const env = Object.fromEntries(pairs) ...Object.entries(process.env),
for (const key of Object.keys(injectedEnvironments)) { ...Object.entries(injectedEnvironments),
env[key] = injectedEnvironments[key] ['NEXT_RUNTIME', 'edge'],
} ])
env.NEXT_RUNTIME = 'edge'
return env return env
} }
......
...@@ -97,7 +97,7 @@ export const EXPORT_DETAIL = 'export-detail.json' ...@@ -97,7 +97,7 @@ export const EXPORT_DETAIL = 'export-detail.json'
export const PRERENDER_MANIFEST = 'prerender-manifest.json' export const PRERENDER_MANIFEST = 'prerender-manifest.json'
export const ROUTES_MANIFEST = 'routes-manifest.json' export const ROUTES_MANIFEST = 'routes-manifest.json'
export const IMAGES_MANIFEST = 'images-manifest.json' export const IMAGES_MANIFEST = 'images-manifest.json'
export const SERVER_FILES_MANIFEST = 'required-server-files.json' export const SERVER_FILES_MANIFEST = 'required-server-files'
export const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json' export const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'
export const MIDDLEWARE_MANIFEST = 'middleware-manifest.json' export const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'
export const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST = export const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST =
......
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