Unverified Commit 4cc5ed45 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Remove web-server from edge-ssr-app (#81389)

Continues https://github.com/vercel/next.js/pull/80915 removing the
final usage of `web-server` from `edge-ssr-app`.

Validated against our deploy E2E tests here
https://github.com/vercel/next.js/actions/runs/16428349930/job/46424359435
and
https://github.com/vercel/vercel/actions/runs/16428657423/job/46425277718?pr=13582

Closes PACK-1824
parent 174a241a
...@@ -155,22 +155,6 @@ async fn wrap_edge_page( ...@@ -155,22 +155,6 @@ async fn wrap_edge_page(
let next_config_val = &*next_config.await?; let next_config_val = &*next_config.await?;
// TODO(WEB-1824): add build support
let dev = true;
// TODO(timneutkens): remove this
let is_server_component = true;
let server_actions = next_config.experimental_server_actions().await?;
let sri_enabled = !dev
&& next_config
.experimental_sri()
.await?
.as_ref()
.map(|sri| sri.algorithm.as_ref())
.is_some();
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(),
...@@ -179,13 +163,9 @@ async fn wrap_edge_page( ...@@ -179,13 +163,9 @@ async fn wrap_edge_page(
"VAR_PAGE" => page.to_string().into(), "VAR_PAGE" => page.to_string().into(),
}, },
fxindexmap! { fxindexmap! {
"sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string().into(),
// TODO do we really need to pass the entire next config here? // TODO do we really need to pass the entire next config here?
// This is bad for invalidation as any config change will invalidate this // This is bad for invalidation as any config change will invalidate this
"nextConfig" => serde_json::to_string(next_config_val)?.into(), "nextConfig" => serde_json::to_string(next_config_val)?.into(),
"isServerComponent" => serde_json::Value::Bool(is_server_component).to_string().into(),
"dev" => serde_json::Value::Bool(dev).to_string().into(),
"serverActions" => serde_json::to_string(&server_actions)?.into(),
}, },
fxindexmap! { fxindexmap! {
"incrementalCacheHandler" => None, "incrementalCacheHandler" => None,
......
...@@ -13,9 +13,6 @@ declare const incrementalCacheHandler: any ...@@ -13,9 +13,6 @@ declare const incrementalCacheHandler: any
// OPTIONAL_IMPORT:* as userland500Page // OPTIONAL_IMPORT:* as userland500Page
// OPTIONAL_IMPORT:incrementalCacheHandler // OPTIONAL_IMPORT:incrementalCacheHandler
// TODO: re-enable this once we've refactored to use implicit matches
// const renderToHTML = undefined
import RouteModule, { import RouteModule, {
type PagesRouteHandlerContext, type PagesRouteHandlerContext,
} from '../../server/route-modules/pages/module' } from '../../server/route-modules/pages/module'
...@@ -342,8 +339,6 @@ async function requestHandler( ...@@ -342,8 +339,6 @@ async function requestHandler(
const tracer = getTracer() const tracer = getTracer()
// TODO: activeSpan code path is for when wrapped by
// next-server can be removed when this is no longer used
return tracer.withPropagatedContext(req.headers, () => return tracer.withPropagatedContext(req.headers, () =>
tracer.trace( tracer.trace(
BaseServerSpan.handleRequest, BaseServerSpan.handleRequest,
......
...@@ -66,7 +66,6 @@ function getRouteModuleOptions(page: string) { ...@@ -66,7 +66,6 @@ function getRouteModuleOptions(page: string) {
const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
async function edgeSSRLoader(this) { async function edgeSSRLoader(this) {
const { const {
dev,
page, page,
absolutePagePath, absolutePagePath,
absoluteAppPath, absoluteAppPath,
...@@ -77,12 +76,10 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -77,12 +76,10 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
stringifiedConfig: stringifiedConfigBase64, stringifiedConfig: stringifiedConfigBase64,
appDirLoader: appDirLoaderBase64, appDirLoader: appDirLoaderBase64,
pagesType, pagesType,
sriEnabled,
cacheHandler, cacheHandler,
cacheHandlers: cacheHandlersStringified, cacheHandlers: cacheHandlersStringified,
preferredRegion, preferredRegion,
middlewareConfig: middlewareConfigBase64, middlewareConfig: middlewareConfigBase64,
serverActions,
} = this.getOptions() } = this.getOptions()
const cacheHandlers = JSON.parse(cacheHandlersStringified || '{}') const cacheHandlers = JSON.parse(cacheHandlersStringified || '{}')
...@@ -158,14 +155,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -158,14 +155,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
VAR_PAGE: page, VAR_PAGE: page,
}, },
{ {
sriEnabled: JSON.stringify(sriEnabled),
nextConfig: stringifiedConfig, nextConfig: stringifiedConfig,
isServerComponent: JSON.stringify(isServerComponent),
dev: JSON.stringify(dev),
serverActions:
typeof serverActions === 'undefined'
? 'undefined'
: JSON.stringify(serverActions),
}, },
{ {
incrementalCacheHandler: cacheHandler ?? null, incrementalCacheHandler: cacheHandler ?? null,
......
import type { NextConfigComplete } from '../../../../server/config-shared'
import type { DocumentType, AppType } from '../../../../shared/lib/utils'
import type { BuildManifest } from '../../../../server/get-page-files'
import type {
DynamicCssManifest,
ReactLoadableManifest,
} from '../../../../server/load-components'
import type { ClientReferenceManifest } from '../../plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../../plugins/next-font-manifest-plugin'
import type { NextFetchEvent } from '../../../../server/web/spec-extension/fetch-event'
import WebServer from '../../../../server/web-server'
import {
WebNextRequest,
WebNextResponse,
} from '../../../../server/base-http/web'
import { SERVER_RUNTIME } from '../../../../lib/constants'
import type { ManifestRewriteRoute } from '../../..'
import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths'
import type { SizeLimit } from '../../../../types'
import { internal_getCurrentFunctionWaitUntil } from '../../../../server/web/internal-edge-wait-until'
import type { PAGE_TYPES } from '../../../../lib/page-types'
import type { NextRequestHint } from '../../../../server/web/adapter'
export function getRender({
dev,
page,
appMod,
pageMod,
errorMod,
error500Mod,
pagesType,
Document,
buildManifest,
reactLoadableManifest,
dynamicCssManifest,
interceptionRouteRewrites,
renderToHTML,
clientReferenceManifest,
subresourceIntegrityManifest,
serverActionsManifest,
serverActions,
config,
buildId,
nextFontManifest,
incrementalCacheHandler,
}: {
pagesType: PAGE_TYPES
dev: boolean
page: string
appMod: any
pageMod: any
errorMod: any
error500Mod: any
renderToHTML?: any
Document: DocumentType
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
dynamicCssManifest?: DynamicCssManifest
subresourceIntegrityManifest?: Record<string, string>
interceptionRouteRewrites?: ManifestRewriteRoute[]
clientReferenceManifest?: ClientReferenceManifest
serverActionsManifest?: any
serverActions?: {
bodySizeLimit?: SizeLimit
allowedOrigins?: string[]
}
config: NextConfigComplete
buildId: string
nextFontManifest: NextFontManifest
incrementalCacheHandler?: any
}) {
const isAppPath = pagesType === 'app'
const baseLoadComponentResult = {
dev,
buildManifest,
reactLoadableManifest,
dynamicCssManifest,
subresourceIntegrityManifest,
Document,
App: appMod?.default as AppType,
clientReferenceManifest,
}
const server = new WebServer({
dev,
buildId,
conf: config,
minimalMode: true,
webServerConfig: {
page,
pathname: isAppPath ? normalizeAppPath(page) : page,
pagesType,
interceptionRouteRewrites,
extendRenderOpts: {
runtime: SERVER_RUNTIME.experimentalEdge,
supportsDynamicResponse: true,
disableOptimizedLoading: true,
serverActionsManifest,
serverActions,
nextFontManifest,
devtoolSegmentExplorer: config.experimental.devtoolSegmentExplorer,
},
renderToHTML,
incrementalCacheHandler,
loadComponent: async (inputPage) => {
if (inputPage === page) {
return {
...baseLoadComponentResult,
Component: pageMod.default,
pageConfig: pageMod.config || {},
getStaticProps: pageMod.getStaticProps,
getServerSideProps: pageMod.getServerSideProps,
getStaticPaths: pageMod.getStaticPaths,
ComponentMod: pageMod,
isAppPath: !!pageMod.__next_app__,
page: inputPage,
routeModule: pageMod.routeModule,
}
}
// If there is a custom 500 page, we need to handle it separately.
if (inputPage === '/500' && error500Mod) {
return {
...baseLoadComponentResult,
Component: error500Mod.default,
pageConfig: error500Mod.config || {},
getStaticProps: error500Mod.getStaticProps,
getServerSideProps: error500Mod.getServerSideProps,
getStaticPaths: error500Mod.getStaticPaths,
ComponentMod: error500Mod,
page: inputPage,
routeModule: error500Mod.routeModule,
}
}
if (inputPage === '/_error') {
return {
...baseLoadComponentResult,
Component: errorMod.default,
pageConfig: errorMod.config || {},
getStaticProps: errorMod.getStaticProps,
getServerSideProps: errorMod.getServerSideProps,
getStaticPaths: errorMod.getStaticPaths,
ComponentMod: errorMod,
page: inputPage,
routeModule: errorMod.routeModule,
}
}
return null
},
},
})
const handler = server.getRequestHandler()
return async function render(
request: NextRequestHint,
event?: NextFetchEvent
) {
const extendedReq = new WebNextRequest(request)
const extendedRes = new WebNextResponse(undefined)
handler(extendedReq, extendedRes)
const result = await extendedRes.toResponse()
request.fetchMetrics = extendedReq.fetchMetrics
if (event?.waitUntil) {
// TODO(after):
// remove `internal_runWithWaitUntil` and the `internal-edge-wait-until` module
// when consumers switch to `after`.
const waitUntilPromise = internal_getCurrentFunctionWaitUntil()
if (waitUntilPromise) {
event.waitUntil(waitUntilPromise)
}
}
return result
}
}
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
} from '../shared/lib/router/utils/interception-routes' } from '../shared/lib/router/utils/interception-routes'
import type { Rewrite } from './load-custom-routes' import type { Rewrite } from './load-custom-routes'
import { safePathToRegexp } from '../shared/lib/router/utils/route-match-utils' import { safePathToRegexp } from '../shared/lib/router/utils/route-match-utils'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
// a function that converts normalised paths (e.g. /foo/[bar]/[baz]) to the format expected by pathToRegexp (e.g. /foo/:bar/:baz) // a function that converts normalised paths (e.g. /foo/[bar]/[baz]) to the format expected by pathToRegexp (e.g. /foo/:bar/:baz)
function toPathToRegexpPath(path: string): string { function toPathToRegexpPath(path: string): string {
...@@ -62,7 +63,7 @@ export function generateInterceptionRoutesRewrites( ...@@ -62,7 +63,7 @@ export function generateInterceptionRoutesRewrites(
return rewrites return rewrites
} }
export function isInterceptionRouteRewrite(route: Rewrite) { export function isInterceptionRouteRewrite(route: DeepReadonly<Rewrite>) {
// When we generate interception rewrites in the above implementation, we always do so with only a single `has` condition. // When we generate interception rewrites in the above implementation, we always do so with only a single `has` condition.
return route.has?.[0]?.key === NEXT_URL return route.has?.[0]?.key === NEXT_URL
} }
...@@ -20,6 +20,14 @@ import type { ServerComponentsHmrCache } from '../../response-cache' ...@@ -20,6 +20,14 @@ import type { ServerComponentsHmrCache } from '../../response-cache'
import type { FallbackRouteParams } from '../../request/fallback-params' import type { FallbackRouteParams } from '../../request/fallback-params'
import { PrerenderManifestMatcher } from './helpers/prerender-manifest-matcher' import { PrerenderManifestMatcher } from './helpers/prerender-manifest-matcher'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_URL,
RSC_HEADER,
} from '../../../client/components/app-router-headers'
import { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/interception-routes'
let vendoredReactRSC let vendoredReactRSC
let vendoredReactSSR let vendoredReactSSR
...@@ -127,6 +135,37 @@ export class AppPageRouteModule extends RouteModule< ...@@ -127,6 +135,37 @@ export class AppPageRouteModule extends RouteModule<
context.sharedContext context.sharedContext
) )
} }
private pathCouldBeIntercepted(
resolvedPathname: string,
interceptionRoutePatterns: RegExp[]
): boolean {
return (
isInterceptionRouteAppPath(resolvedPathname) ||
interceptionRoutePatterns.some((regexp) => {
return regexp.test(resolvedPathname)
})
)
}
public getVaryHeader(
resolvedPathname: string,
interceptionRoutePatterns: RegExp[]
): string {
const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`
if (
this.pathCouldBeIntercepted(resolvedPathname, interceptionRoutePatterns)
) {
// Interception route responses can vary based on the `Next-URL` header.
// We use the Vary header to signal this behavior to the client to properly cache the response.
return `${baseVaryHeader}, ${NEXT_URL}`
} else {
// We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.
// We also set this header for pages to avoid caching issues when navigating between pages and app.
return baseVaryHeader
}
}
} }
const vendored = { const vendored = {
......
...@@ -60,6 +60,7 @@ import { ...@@ -60,6 +60,7 @@ import {
} from '../lib/router-utils/router-server-context' } from '../lib/router-utils/router-server-context'
import { decodePathParams } from '../lib/router-utils/decode-path-params' import { decodePathParams } from '../lib/router-utils/decode-path-params'
import { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash'
import { isInterceptionRouteRewrite } from '../../lib/generate-interception-routes-rewrites'
/** /**
* RouteModuleOptions is the options that are passed to the route module, other * RouteModuleOptions is the options that are passed to the route module, other
...@@ -181,6 +182,7 @@ export abstract class RouteModule< ...@@ -181,6 +182,7 @@ export abstract class RouteModule<
clientReferenceManifest: any clientReferenceManifest: any
serverActionsManifest: any serverActionsManifest: any
dynamicCssManifest: any dynamicCssManifest: any
interceptionRoutePatterns: RegExp[]
} { } {
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
const { getEdgePreviewProps } = const { getEdgePreviewProps } =
...@@ -227,6 +229,9 @@ export abstract class RouteModule< ...@@ -227,6 +229,9 @@ export abstract class RouteModule<
self.__SUBRESOURCE_INTEGRITY_MANIFEST self.__SUBRESOURCE_INTEGRITY_MANIFEST
), ),
dynamicCssManifest: maybeJSONParse(self.__DYNAMIC_CSS_MANIFEST), dynamicCssManifest: maybeJSONParse(self.__DYNAMIC_CSS_MANIFEST),
interceptionRoutePatterns: (
maybeJSONParse(self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST) ?? []
).map((rewrite: any) => new RegExp(rewrite.regex)),
} }
} else { } else {
if (!projectDir) { if (!projectDir) {
...@@ -344,12 +349,15 @@ export abstract class RouteModule< ...@@ -344,12 +349,15 @@ export abstract class RouteModule<
serverActionsManifest, serverActionsManifest,
subresourceIntegrityManifest, subresourceIntegrityManifest,
dynamicCssManifest, dynamicCssManifest,
interceptionRoutePatterns: routesManifest.rewrites.beforeFiles
.filter(isInterceptionRouteRewrite)
.map((rewrite) => new RegExp(rewrite.regex)),
} }
} }
} }
public async loadCustomCacheHandlers( public async loadCustomCacheHandlers(
req: IncomingMessage, req: IncomingMessage | BaseNextRequest,
nextConfig: NextConfigComplete nextConfig: NextConfigComplete
) { ) {
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
...@@ -387,7 +395,7 @@ export abstract class RouteModule< ...@@ -387,7 +395,7 @@ export abstract class RouteModule<
} }
public async getIncrementalCache( public async getIncrementalCache(
req: IncomingMessage, req: IncomingMessage | BaseNextRequest,
nextConfig: NextConfigComplete, nextConfig: NextConfigComplete,
prerenderManifest: DeepReadonly<PrerenderManifest> prerenderManifest: DeepReadonly<PrerenderManifest>
): Promise<IncrementalCache> { ): Promise<IncrementalCache> {
...@@ -501,6 +509,7 @@ export abstract class RouteModule< ...@@ -501,6 +509,7 @@ export abstract class RouteModule<
revalidateOnlyGenerated: boolean revalidateOnlyGenerated: boolean
nextConfig: NextConfigComplete nextConfig: NextConfigComplete
routerServerContext?: RouterServerContext[string] routerServerContext?: RouterServerContext[string]
interceptionRoutePatterns?: any
} }
| undefined | undefined
> { > {
...@@ -809,7 +818,7 @@ export abstract class RouteModule< ...@@ -809,7 +818,7 @@ export abstract class RouteModule<
} }
} }
public getResponseCache(req: IncomingMessage) { public getResponseCache(req: IncomingMessage | BaseNextRequest) {
if (!this.responseCache) { if (!this.responseCache) {
const minimalMode = getRequestMeta(req, 'minimalMode') ?? false const minimalMode = getRequestMeta(req, 'minimalMode') ?? false
this.responseCache = new ResponseCache(minimalMode) this.responseCache = new ResponseCache(minimalMode)
...@@ -830,7 +839,7 @@ export abstract class RouteModule< ...@@ -830,7 +839,7 @@ export abstract class RouteModule<
responseGenerator, responseGenerator,
waitUntil, waitUntil,
}: { }: {
req: IncomingMessage req: IncomingMessage | BaseNextRequest
nextConfig: NextConfigComplete nextConfig: NextConfigComplete
cacheKey: string | null cacheKey: string | null
routeKind: RouteKind routeKind: RouteKind
......
This diff is collapsed.
...@@ -95,11 +95,13 @@ function enhanceGlobals() { ...@@ -95,11 +95,13 @@ function enhanceGlobals() {
// to allow building code that import but does not use node.js modules, // to allow building code that import but does not use node.js modules,
// webpack will expect this function to exist in global scope // webpack will expect this function to exist in global scope
Object.defineProperty(globalThis, '__import_unsupported', { try {
value: __import_unsupported, Object.defineProperty(globalThis, '__import_unsupported', {
enumerable: false, value: __import_unsupported,
configurable: false, enumerable: false,
}) configurable: false,
})
} catch {}
// Eagerly fire instrumentation hook to make the startup faster. // Eagerly fire instrumentation hook to make the startup faster.
void ensureInstrumentationRegistered() void ensureInstrumentationRegistered()
......
...@@ -13,6 +13,10 @@ import { ...@@ -13,6 +13,10 @@ import {
getBuiltinRequestContext, getBuiltinRequestContext,
type BuiltinRequestContextValue, type BuiltinRequestContextValue,
} from '../../after/builtin-request-context' } from '../../after/builtin-request-context'
import {
RouterServerContextSymbol,
routerServerGlobal,
} from '../../lib/router-utils/router-server-context'
export const ErrorSource = Symbol('SandboxError') export const ErrorSource = Symbol('SandboxError')
...@@ -81,6 +85,12 @@ export async function getRuntimeContext( ...@@ -81,6 +85,12 @@ export async function getRuntimeContext(
runtime.context.globalThis.__incrementalCache = params.incrementalCache runtime.context.globalThis.__incrementalCache = params.incrementalCache
} }
// expose router server context for access to dev handlers like
// logErrorWithOriginalStack
;(runtime.context.globalThis as any as typeof routerServerGlobal)[
RouterServerContextSymbol
] = routerServerGlobal[RouterServerContextSymbol]
if (params.serverComponentsHmrCache) { if (params.serverComponentsHmrCache) {
runtime.context.globalThis.__serverComponentsHmrCache = runtime.context.globalThis.__serverComponentsHmrCache =
params.serverComponentsHmrCache params.serverComponentsHmrCache
......
...@@ -152,19 +152,14 @@ describe('unrecognized server actions', () => { ...@@ -152,19 +152,14 @@ describe('unrecognized server actions', () => {
if (isNextDeploy) { if (isNextDeploy) {
// FIXME: When deployed to vercel, the request is logged as a 500, but returns a 405. // FIXME: When deployed to vercel, the request is logged as a 500, but returns a 405.
// We also don't seem to display the error page correctly, // We also don't seem to display the error page correctly
// and the response is inconsistent between nodejs and edge. expect(response.status()).toBe(405)
expect(response.status()).toBe(runtime === 'nodejs' ? 405 : 500) expect(response.headers()['content-type']).toStartWith('text/html')
expect(response.headers()['content-type']).toStartWith(
runtime === 'nodejs' ? 'text/html' : 'text/plain'
)
} else { } else {
// FIXME: Currently, an unrecognized id in an MPA action results in a 500. // FIXME: Currently, an unrecognized id in an MPA action results in a 500.
// This is not ideal, and ignores all nested `error.js` files, only showing the topmost one. // This is not ideal, and ignores all nested `error.js` files, only showing the topmost one.
expect(response.status()).toBe(500) expect(response.status()).toBe(500)
expect(response.headers()['content-type']).toStartWith( expect(response.headers()['content-type']).toStartWith('text/html')
runtime === 'nodejs' ? 'text/html' : 'text/plain'
)
// In dev, the 500 page doesn't have any SSR'd html, so it won't show anything without JS. // In dev, the 500 page doesn't have any SSR'd html, so it won't show anything without JS.
if (!isNextDev) { if (!isNextDev) {
expect(await browser.elementByCss('body').text()).toContain( expect(await browser.elementByCss('body').text()).toContain(
......
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