Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions crates/next-api/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1543,6 +1543,9 @@ impl AppEndpoint {
rcstr!("server/middleware-build-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 {
file_paths_from_root.insert(rcstr!("server/next-font-manifest.js"));
};
Expand Down
11 changes: 10 additions & 1 deletion crates/next-api/src/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,6 @@ impl PageEndpoint {
this.original_name.clone(),
*this.pages_structure,
runtime,
this.pages_project.project().next_config(),
)
.await?;

Expand Down Expand Up @@ -1441,6 +1440,16 @@ impl PageEndpoint {
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 assets_ref = assets.await?;

Expand Down
10 changes: 1 addition & 9 deletions crates/next-core/src/next_app/app_page_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ pub async fn get_app_page_entry(
project_root.clone(),
rsc_entry,
page,
next_config,
);
};

Expand All @@ -141,21 +140,14 @@ async fn wrap_edge_page(
project_root: FileSystemPath,
entry: ResolvedVc<Box<dyn Module>>,
page: AppPage,
next_config: Vc<NextConfig>,
) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_PAGE_ENTRY";

let next_config_val = &*next_config.await?;

let source = load_next_js_template(
"edge-ssr-app.js",
project_root.clone(),
[("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)],
)
.await?;
Expand Down
6 changes: 1 addition & 5 deletions crates/next-core/src/next_app/app_route_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ pub async fn get_app_route_entry(
project_root,
rsc_entry,
page,
next_config,
);
}

Expand All @@ -132,17 +131,14 @@ async fn wrap_edge_route(
project_root: FileSystemPath,
entry: ResolvedVc<Box<dyn Module>>,
page: AppPage,
next_config: Vc<NextConfig>,
) -> Result<Vc<Box<dyn Module>>> {
let inner = rcstr!("INNER_ROUTE_ENTRY");

let next_config = &*next_config.await?;

let source = load_next_js_template(
"edge-app-route.js",
project_root.clone(),
[("VAR_USERLAND", &*inner), ("VAR_PAGE", &page.to_string())],
[("nextConfig", &*serde_json::to_string(next_config)?)],
[],
[],
)
.await?;
Expand Down
6 changes: 0 additions & 6 deletions crates/next-core/src/next_pages/page_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use turbopack_core::{
};

use crate::{
next_config::NextConfig,
next_edge::entry::wrap_edge_entry,
pages_structure::{PagesStructure, PagesStructureItem},
util::{NextRuntime, file_content_rope, load_next_js_template, pages_function_name},
Expand All @@ -39,7 +38,6 @@ pub async fn create_page_ssr_entry_module(
next_original_name: RcStr,
pages_structure: Vc<PagesStructure>,
runtime: NextRuntime,
next_config: Vc<NextConfig>,
) -> Result<Vc<PageSsrEntryModule>> {
let definition_page = next_original_name;
let definition_pathname = pathname;
Expand Down Expand Up @@ -99,11 +97,7 @@ pub async fn create_page_ssr_entry_module(
let pages_structure_ref = pages_structure.await?;

let (injections, imports) = if is_page && runtime == NextRuntime::Edge {
let next_config_val = &*next_config.await?;
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",
serde_json::to_string(&get_route_module_options(
Expand Down
4 changes: 3 additions & 1 deletion packages/next/errors.json
Original file line number Diff line number Diff line change
Expand Up @@ -965,5 +965,7 @@
"964": "An unexpected error occurred while starting to capture immediates",
"965": "Expected setImmediate 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"
}
2 changes: 1 addition & 1 deletion packages/next/src/build/define-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ export function getDefineEnv({
config.experimental.trustHostHeader ?? false,
'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS':
config.experimental.allowedRevalidateHeaderKeys ?? [],
...(isNodeServer
...(isNodeServer || isEdgeServer
? {
'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir,
'process.env.__NEXT_RELATIVE_PROJECT_DIR': path.relative(
Expand Down
4 changes: 0 additions & 4 deletions packages/next/src/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,6 @@ export function getEdgeServerEntry(opts: {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
nextConfig: Buffer.from(JSON.stringify(opts.config)).toString('base64'),
preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {})
Expand Down Expand Up @@ -682,9 +681,6 @@ export function getEdgeServerEntry(opts: {
dev: opts.isDev,
isServerComponent: opts.isServerComponent,
page: opts.page,
stringifiedConfig: Buffer.from(JSON.stringify(opts.config)).toString(
'base64'
),
pagesType: opts.pagesType,
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm,
Expand Down
13 changes: 10 additions & 3 deletions packages/next/src/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,9 +621,13 @@ async function writeRequiredServerFilesManifest(
requiredServerFiles: RequiredServerFilesManifest
) {
await writeManifest(
path.join(distDir, SERVER_FILES_MANIFEST),
path.join(distDir, SERVER_FILES_MANIFEST + '.json'),
requiredServerFiles
)
await writeFileUtf8(
path.join(distDir, SERVER_FILES_MANIFEST + '.js'),
`self.__SERVER_FILES_MANIFEST=${formatManifest(requiredServerFiles)}`
)
}

async function writeImagesManifest(
Expand Down Expand Up @@ -693,7 +697,10 @@ async function writeStandaloneDirectory(

for (const file of [
...requiredServerFiles.files,
path.join(requiredServerFiles.config.distDir, SERVER_FILES_MANIFEST),
path.join(
requiredServerFiles.config.distDir,
SERVER_FILES_MANIFEST + '.json'
),
...loadedEnvFiles.reduce<string[]>((acc, envFile) => {
if (['.env', '.env.production'].includes(envFile.path)) {
acc.push(envFile.path)
Expand Down Expand Up @@ -1915,7 +1922,7 @@ export default async function build(
BUILD_ID_FILE,
path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.js'),
path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.json'),
SERVER_FILES_MANIFEST,
SERVER_FILES_MANIFEST + '.json',
]
.filter(nonNullable)
.map((file) => path.join(config.distDir, file)),
Expand Down
4 changes: 0 additions & 4 deletions packages/next/src/build/templates/edge-app-route.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import type { NextConfigRuntime } from '../../server/config-shared'
import type { EdgeHandler } from '../../server/web/adapter'
import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper'

// Import the userland code.
import * as module from 'VAR_USERLAND'

// injected by the loader afterwards.
declare const nextConfig: NextConfigRuntime
// INJECT:nextConfig

const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)

Expand All @@ -26,7 +23,6 @@ if (rscManifest && rscServerManifest) {
export const ComponentMod = module

const handler: EdgeHandler = EdgeRouteModuleWrapper.wrap(module.routeModule, {
nextConfig,
page: 'VAR_PAGE',
})
export default handler
10 changes: 4 additions & 6 deletions packages/next/src/build/templates/edge-ssr-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { IncrementalCache } from '../../server/lib/incremental-cache'

import * as pageMod from 'VAR_USERLAND'

import type { NextConfigRuntime } from '../../server/config-shared'
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { initializeCacheHandlers } from '../../server/use-cache/handlers'
import { BaseServerSpan } from '../../server/lib/trace/constants'
Expand All @@ -29,12 +28,7 @@ import { checkIsOnDemandRevalidate } from '../../server/api-utils'
import { CloseController } from '../../server/web/web-on-close'

declare const incrementalCacheHandler: any
declare const nextConfig: NextConfigRuntime
// OPTIONAL_IMPORT:incrementalCacheHandler
// INJECT:nextConfig

// Initialize the cache handlers interface.
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)

const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)

Expand Down Expand Up @@ -77,6 +71,7 @@ async function requestHandler(
query,
params,
buildId,
nextConfig,
buildManifest,
prerenderManifest,
reactLoadableManifest,
Expand All @@ -88,6 +83,9 @@ async function requestHandler(
routerServerContext,
} = prepareResult

// Initialize the cache handlers interface.
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)

const isPossibleServerAction = getIsPossibleServerAction(req)
const botType = getBotType(req.headers.get('User-Agent') || '')
const { isOnDemandRevalidate } = checkIsOnDemandRevalidate(
Expand Down
18 changes: 9 additions & 9 deletions packages/next/src/build/templates/edge-ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import RouteModule, {
} from '../../server/route-modules/pages/module'
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 RenderResult from '../../server/render-result'
import type { RenderResultMetadata } from '../../server/render-result'
Expand All @@ -31,21 +30,13 @@ import { BaseServerSpan } from '../../server/lib/trace/constants'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'

// injected by the loader afterwards.
declare const nextConfig: NextConfigRuntime
declare const pageRouteModuleOptions: any
declare const errorRouteModuleOptions: any
declare const user500RouteModuleOptions: any
// INJECT:nextConfig
// INJECT:pageRouteModuleOptions
// INJECT:errorRouteModuleOptions
// INJECT:user500RouteModuleOptions

// Initialize the cache handlers interface.
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)

// expose this for the route-module
;(globalThis as any).nextConfig = nextConfig

const pageMod = {
...userlandPage,
routeModule: new RouteModule({
Expand All @@ -55,6 +46,8 @@ const pageMod = {
Document,
},
userland: userlandPage,
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
}),
}

Expand All @@ -67,6 +60,8 @@ const errorMod = {
Document,
},
userland: userlandErrorPage,
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
}),
}

Expand All @@ -81,6 +76,8 @@ const error500Mod = userland500Page
Document,
},
userland: userland500Page,
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
}),
}
: null
Expand Down Expand Up @@ -110,6 +107,7 @@ async function requestHandler(
query,
params,
buildId,
nextConfig,
isNextDataRequest,
buildManifest,
prerenderManifest,
Expand All @@ -119,6 +117,8 @@ async function requestHandler(
dynamicCssManifest,
} = prepareResult

initializeCacheHandlers(nextConfig.cacheMaxMemorySize)

const renderContext: PagesRouteHandlerContext = {
page: srcPage,
query,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ export type EdgeAppRouteLoaderQuery = {
page: string
appDirLoader: string
preferredRegion: string | string[] | undefined
nextConfig: string
middlewareConfig: string
cacheHandlers: string
}
Expand All @@ -24,7 +23,6 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
preferredRegion,
appDirLoader: appDirLoaderBase64 = '',
middlewareConfig: middlewareConfigBase64 = '',
nextConfig: nextConfigBase64,
cacheHandlers: cacheHandlersStringified,
} = this.getOptions()

Expand Down Expand Up @@ -64,20 +62,13 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
stringifiedPagePath.length - 1
)}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}`

const stringifiedConfig = Buffer.from(
nextConfigBase64 || '',
'base64'
).toString()

return await loadEntrypoint(
'edge-app-route',
{
VAR_USERLAND: modulePath,
VAR_PAGE: page,
},
{
nextConfig: stringifiedConfig,
}
{}
)
}

Expand Down
Loading
Loading