Unverified Commit 074262ba authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Only allow node runtime in proxy (#85139)

This PR is the initiative of deprecating the edge runtime. Proxy will
default to Node.js runtime, and will not allow runtime config. If the
users want to use the edge runtime, they should stay on the Middleware,
though we recommend starting the migration.

---------
Co-authored-by: 's avatardevjiwonchoi <devjiwonchoi@gmail.com>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 47ceda3c
...@@ -4322,7 +4322,6 @@ dependencies = [ ...@@ -4322,7 +4322,6 @@ dependencies = [
"next-custom-transforms", "next-custom-transforms",
"next-taskless", "next-taskless",
"once_cell", "once_cell",
"pathdiff",
"percent-encoding", "percent-encoding",
"qstring", "qstring",
"react_remove_properties", "react_remove_properties",
......
...@@ -6,8 +6,7 @@ use next_core::{ ...@@ -6,8 +6,7 @@ use next_core::{
middleware::get_middleware_module, middleware::get_middleware_module,
next_edge::entry::wrap_edge_entry, next_edge::entry::wrap_edge_entry,
next_manifests::{EdgeFunctionDefinition, MiddlewaresManifestV2, ProxyMatcher, Regions}, next_manifests::{EdgeFunctionDefinition, MiddlewaresManifestV2, ProxyMatcher, Regions},
parse_segment_config_from_source, segment_config::NextSegmentConfig,
segment_config::ParseSegmentMode,
util::{MiddlewareMatcherKind, NextRuntime}, util::{MiddlewareMatcherKind, NextRuntime},
}; };
use tracing::Instrument; use tracing::Instrument;
...@@ -49,6 +48,8 @@ pub struct MiddlewareEndpoint { ...@@ -49,6 +48,8 @@ pub struct MiddlewareEndpoint {
source: ResolvedVc<Box<dyn Source>>, source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<FileSystemPath>, app_dir: Option<FileSystemPath>,
ecmascript_client_reference_transition_name: Option<RcStr>, ecmascript_client_reference_transition_name: Option<RcStr>,
config: ResolvedVc<NextSegmentConfig>,
runtime: NextRuntime,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -60,6 +61,8 @@ impl MiddlewareEndpoint { ...@@ -60,6 +61,8 @@ impl MiddlewareEndpoint {
source: ResolvedVc<Box<dyn Source>>, source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<FileSystemPath>, app_dir: Option<FileSystemPath>,
ecmascript_client_reference_transition_name: Option<RcStr>, ecmascript_client_reference_transition_name: Option<RcStr>,
config: ResolvedVc<NextSegmentConfig>,
runtime: NextRuntime,
) -> Vc<Self> { ) -> Vc<Self> {
Self { Self {
project, project,
...@@ -67,6 +70,8 @@ impl MiddlewareEndpoint { ...@@ -67,6 +70,8 @@ impl MiddlewareEndpoint {
source, source,
app_dir, app_dir,
ecmascript_client_reference_transition_name, ecmascript_client_reference_transition_name,
config,
runtime,
} }
.cell() .cell()
} }
...@@ -81,20 +86,20 @@ impl MiddlewareEndpoint { ...@@ -81,20 +86,20 @@ impl MiddlewareEndpoint {
) )
.module(); .module();
let userland_path = userland_module.ident().path().await?;
let is_proxy = userland_path.file_stem() == Some("proxy");
let module = get_middleware_module( let module = get_middleware_module(
*self.asset_context, *self.asset_context,
self.project.project_path().owned().await?, self.project.project_path().owned().await?,
userland_module, userland_module,
is_proxy,
); );
let runtime = parse_segment_config_from_source(*self.source, ParseSegmentMode::Base) if matches!(self.runtime, NextRuntime::NodeJs) {
.await?
.runtime
.unwrap_or(NextRuntime::Edge);
if matches!(runtime, NextRuntime::NodeJs) {
return Ok(module); return Ok(module);
} }
Ok(wrap_edge_entry( Ok(wrap_edge_entry(
*self.asset_context, *self.asset_context,
self.project.project_path().owned().await?, self.project.project_path().owned().await?,
...@@ -152,10 +157,7 @@ impl MiddlewareEndpoint { ...@@ -152,10 +157,7 @@ impl MiddlewareEndpoint {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> { async fn output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> {
let this = self.await?; let this = self.await?;
let config = this.config.await?;
let config =
parse_segment_config_from_source(*self.await?.source, ParseSegmentMode::Base).await?;
let runtime = config.runtime.unwrap_or(NextRuntime::Edge);
let next_config = this.project.next_config(); let next_config = this.project.next_config();
let i18n = next_config.i18n().await?; let i18n = next_config.i18n().await?;
...@@ -223,7 +225,7 @@ impl MiddlewareEndpoint { ...@@ -223,7 +225,7 @@ impl MiddlewareEndpoint {
}] }]
}; };
if matches!(runtime, NextRuntime::NodeJs) { if matches!(this.runtime, NextRuntime::NodeJs) {
let chunk = self.node_chunk().to_resolved().await?; let chunk = self.node_chunk().to_resolved().await?;
let mut output_assets = vec![chunk]; let mut output_assets = vec![chunk];
if this.project.next_mode().await?.is_production() { if this.project.next_mode().await?.is_production() {
......
...@@ -1437,28 +1437,6 @@ impl Project { ...@@ -1437,28 +1437,6 @@ impl Project {
))) )))
} }
#[turbo_tasks::function]
async fn middleware_context(self: Vc<Self>) -> Result<Vc<Box<dyn AssetContext>>> {
let edge_module_context = self.edge_middleware_context();
let middleware = self.find_middleware();
let FindContextFileResult::Found(fs_path, _) = &*middleware.await? else {
return Ok(edge_module_context);
};
let source = Vc::upcast(FileSource::new(fs_path.clone()));
let runtime = parse_segment_config_from_source(source, ParseSegmentMode::Base)
.await?
.runtime
.unwrap_or(NextRuntime::Edge);
if matches!(runtime, NextRuntime::NodeJs) {
Ok(self.node_middleware_context())
} else {
Ok(edge_module_context)
}
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn find_middleware(self: Vc<Self>) -> Result<Vc<FindContextFileResult>> { async fn find_middleware(self: Vc<Self>) -> Result<Vc<FindContextFileResult>> {
Ok(find_context_file( Ok(find_context_file(
...@@ -1483,7 +1461,25 @@ impl Project { ...@@ -1483,7 +1461,25 @@ impl Project {
.as_ref() .as_ref()
.map(|_| AppProject::client_transition_name()); .map(|_| AppProject::client_transition_name());
let middleware_asset_context = self.middleware_context(); let is_proxy = fs_path.file_stem() == Some("proxy");
let config = parse_segment_config_from_source(
source,
if is_proxy {
ParseSegmentMode::Proxy
} else {
ParseSegmentMode::Base
},
);
let runtime = config.await?.runtime.unwrap_or(if is_proxy {
NextRuntime::NodeJs
} else {
NextRuntime::Edge
});
let middleware_asset_context = match runtime {
NextRuntime::NodeJs => self.node_middleware_context(),
NextRuntime::Edge => self.edge_middleware_context(),
};
Ok(Vc::upcast(MiddlewareEndpoint::new( Ok(Vc::upcast(MiddlewareEndpoint::new(
self, self,
...@@ -1491,6 +1487,8 @@ impl Project { ...@@ -1491,6 +1487,8 @@ impl Project {
source, source,
app_dir.clone(), app_dir.clone(),
ecmascript_client_reference_transition_name, ecmascript_client_reference_transition_name,
config,
runtime,
))) )))
} }
......
...@@ -32,12 +32,12 @@ pub async fn get_middleware_module( ...@@ -32,12 +32,12 @@ pub async fn get_middleware_module(
asset_context: Vc<Box<dyn AssetContext>>, asset_context: Vc<Box<dyn AssetContext>>,
project_root: FileSystemPath, project_root: FileSystemPath,
userland_module: ResolvedVc<Box<dyn Module>>, userland_module: ResolvedVc<Box<dyn Module>>,
is_proxy: bool,
) -> Result<Vc<Box<dyn Module>>> { ) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_MIDDLEWARE_MODULE"; const INNER: &str = "INNER_MIDDLEWARE_MODULE";
// Determine if this is a proxy file by checking the module path // Determine if this is a proxy file by checking the module path
let userland_path = userland_module.ident().path().await?; let userland_path = userland_module.ident().path().await?;
let is_proxy = userland_path.file_stem() == Some("proxy");
let (file_type, function_name, page_path) = if is_proxy { let (file_type, function_name, page_path) = if is_proxy {
("Proxy", "proxy", "/proxy") ("Proxy", "proxy", "/proxy")
} else { } else {
...@@ -91,11 +91,7 @@ pub async fn get_middleware_module( ...@@ -91,11 +91,7 @@ pub async fn get_middleware_module(
let source = load_next_js_template( let source = load_next_js_template(
"middleware.js", "middleware.js",
project_root, project_root,
&[ &[("VAR_USERLAND", INNER), ("VAR_DEFINITION_PAGE", page_path)],
("VAR_USERLAND", INNER),
("VAR_DEFINITION_PAGE", page_path),
("VAR_MODULE_RELATIVE_PATH", userland_path.path.as_str()),
],
&[], &[],
&[], &[],
) )
......
...@@ -289,6 +289,8 @@ pub enum ParseSegmentMode { ...@@ -289,6 +289,8 @@ pub enum ParseSegmentMode {
Base, Base,
// Disallows "use client + generateStatic" and ignores/warns about `export const config` // Disallows "use client + generateStatic" and ignores/warns about `export const config`
App, App,
// Disallows config = { runtime: "edge" }
Proxy,
} }
/// Parse the raw source code of a file to get the segment config local to that file. /// Parse the raw source code of a file to get the segment config local to that file.
...@@ -667,21 +669,35 @@ async fn parse_config_value( ...@@ -667,21 +669,35 @@ async fn parse_config_value(
.await; .await;
}; };
config.runtime = let runtime = match serde_json::from_value(Value::String(val.to_string())) {
match serde_json::from_value(Value::String(val.to_string())) { Ok(runtime) => Some(runtime),
Ok(runtime) => Some(runtime), Err(err) => {
Err(err) => { return invalid_config(
return invalid_config( source,
source, "config",
"config", span,
span, format!("`runtime` has an invalid value: {err}.").into(),
format!("`runtime` has an invalid value: {err}.").into(), Some(value),
Some(value), IssueSeverity::Error,
IssueSeverity::Error, )
) .await;
.await; }
} };
};
if mode == ParseSegmentMode::Proxy && runtime == Some(NextRuntime::Edge) {
invalid_config(
source,
"config",
span,
rcstr!("Proxy does not support Edge runtime."),
Some(value),
IssueSeverity::Error,
)
.await?;
continue;
}
config.runtime = runtime
} }
"matcher" => { "matcher" => {
config.middleware_matcher = config.middleware_matcher =
......
...@@ -901,5 +901,6 @@ ...@@ -901,5 +901,6 @@
"900": "Both %s file \"./%s\" and %s file \"./%s\" are detected. Please use \"./%s\" only. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy", "900": "Both %s file \"./%s\" and %s file \"./%s\" are detected. Please use \"./%s\" only. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy",
"901": "Invalid \"cacheHandlers\" provided, expected an object e.g. { default: '/my-handler.js' }, received %s", "901": "Invalid \"cacheHandlers\" provided, expected an object e.g. { default: '/my-handler.js' }, received %s",
"902": "Invalid handler fields configured for \"cacheHandlers\":\\n%s", "902": "Invalid handler fields configured for \"cacheHandlers\":\\n%s",
"903": "The file \"%s\" must export a function, either as a default export or as a named \"%s\" export.\\nThis function is what Next.js runs for every request handled by this %s.\\n\\nWhy this happens:\\n%s- The file exists but doesn't export a function.\\n- The export is not a function (e.g., an object or constant).\\n- There's a syntax error preventing the export from being recognized.\\n\\nTo fix it:\\n- Ensure this file has either a default or \"%s\" function export.\\n\\nLearn more: https://nextjs.org/docs/messages/middleware-to-proxy" "903": "The file \"%s\" must export a function, either as a default export or as a named \"%s\" export.\\nThis function is what Next.js runs for every request handled by this %s.\\n\\nWhy this happens:\\n%s- The file exists but doesn't export a function.\\n- The export is not a function (e.g., an object or constant).\\n- There's a syntax error preventing the export from being recognized.\\n\\nTo fix it:\\n- Ensure this file has either a default or \"%s\" function export.\\n\\nLearn more: https://nextjs.org/docs/messages/middleware-to-proxy",
"904": "The file \"%s\" must export a function, either as a default export or as a named \"%s\" export."
} }
...@@ -40,6 +40,7 @@ import { ...@@ -40,6 +40,7 @@ import {
} from '../segment-config/middleware/middleware-config' } from '../segment-config/middleware/middleware-config'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { isProxyFile } from '../utils'
const PARSE_PATTERN = const PARSE_PATTERN =
/(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const|generateImageMetadata|generateSitemaps|middleware|proxy/ /(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const|generateImageMetadata|generateSitemaps|middleware|proxy/
...@@ -305,16 +306,13 @@ function validateMiddlewareProxyExports({ ...@@ -305,16 +306,13 @@ function validateMiddlewareProxyExports({
ast, ast,
page, page,
pageFilePath, pageFilePath,
isDev,
}: { }: {
ast: any ast: any
page: string page: string
pageFilePath: string pageFilePath: string
isDev: boolean
}): void { }): void {
// Only validate in build. In development, it will error at runtime.
if (process.env.NODE_ENV !== 'production') {
return
}
// Check if this is middleware/proxy // Check if this is middleware/proxy
const isMiddleware = const isMiddleware =
page === `/${MIDDLEWARE_FILENAME}` || page === `/src/${MIDDLEWARE_FILENAME}` page === `/${MIDDLEWARE_FILENAME}` || page === `/src/${MIDDLEWARE_FILENAME}`
...@@ -396,23 +394,33 @@ function validateMiddlewareProxyExports({ ...@@ -396,23 +394,33 @@ function validateMiddlewareProxyExports({
(isMiddleware && hasMiddlewareExport) || (isMiddleware && hasMiddlewareExport) ||
(isProxy && hasProxyExport) (isProxy && hasProxyExport)
const relativeFilePath = `./${relative(process.cwd(), pageFilePath)}` const relativePath = relative(process.cwd(), pageFilePath)
const resolvedPath = relativePath.startsWith('.')
? relativePath
: `./${relativePath}`
if (!hasValidExport) { if (!hasValidExport) {
throw new Error( const message =
`The file "${relativeFilePath}" must export a function, either as a default export or as a named "${fileName}" export.\n` + `The file "${resolvedPath}" must export a function, either as a default export or as a named "${fileName}" export.\n` +
`This function is what Next.js runs for every request handled by this ${fileName === 'proxy' ? 'proxy (previously called middleware)' : 'middleware'}.\n\n` + `This function is what Next.js runs for every request handled by this ${fileName === 'proxy' ? 'proxy (previously called middleware)' : 'middleware'}.\n\n` +
`Why this happens:\n` + `Why this happens:\n` +
(isProxy (isProxy
? "- You are migrating from `middleware` to `proxy`, but haven't updated the exported function.\n" ? "- You are migrating from `middleware` to `proxy`, but haven't updated the exported function.\n"
: '') + : '') +
`- The file exists but doesn't export a function.\n` + `- The file exists but doesn't export a function.\n` +
`- The export is not a function (e.g., an object or constant).\n` + `- The export is not a function (e.g., an object or constant).\n` +
`- There's a syntax error preventing the export from being recognized.\n\n` + `- There's a syntax error preventing the export from being recognized.\n\n` +
`To fix it:\n` + `To fix it:\n` +
`- Ensure this file has either a default or "${fileName}" function export.\n\n` + `- Ensure this file has either a default or "${fileName}" function export.\n\n` +
`Learn more: https://nextjs.org/docs/messages/middleware-to-proxy` `Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
)
if (isDev) {
// errorOnce as proxy/middleware runs per request including multiple
// internal _next/ routes and spams logs.
Log.errorOnce(message)
} else {
throw new Error(message)
}
} }
} }
...@@ -593,7 +601,7 @@ function warnAboutUnsupportedValue( ...@@ -593,7 +601,7 @@ function warnAboutUnsupportedValue(
type GetPageStaticInfoParams = { type GetPageStaticInfoParams = {
pageFilePath: string pageFilePath: string
nextConfig: Partial<NextConfig> nextConfig: Partial<NextConfig>
isDev?: boolean isDev: boolean
page: string page: string
pageType: PAGE_TYPES pageType: PAGE_TYPES
} }
...@@ -617,7 +625,12 @@ export async function getAppPageStaticInfo({ ...@@ -617,7 +625,12 @@ export async function getAppPageStaticInfo({
} }
const ast = await parseModule(pageFilePath, content) const ast = await parseModule(pageFilePath, content)
validateMiddlewareProxyExports({ ast, page, pageFilePath }) validateMiddlewareProxyExports({
ast,
page,
pageFilePath,
isDev,
})
const { const {
generateStaticParams, generateStaticParams,
...@@ -713,7 +726,12 @@ export async function getPagesPageStaticInfo({ ...@@ -713,7 +726,12 @@ export async function getPagesPageStaticInfo({
} }
const ast = await parseModule(pageFilePath, content) const ast = await parseModule(pageFilePath, content)
validateMiddlewareProxyExports({ ast, page, pageFilePath }) validateMiddlewareProxyExports({
ast,
page,
pageFilePath,
isDev,
})
const { getServerSideProps, getStaticProps, exports } = checkExports( const { getServerSideProps, getStaticProps, exports } = checkExports(
ast, ast,
...@@ -750,13 +768,35 @@ export async function getPagesPageStaticInfo({ ...@@ -750,13 +768,35 @@ export async function getPagesPageStaticInfo({
const config = parsePagesSegmentConfig(exportedConfig, route) const config = parsePagesSegmentConfig(exportedConfig, route)
const isAnAPIRoute = isAPIRoute(route) const isAnAPIRoute = isAPIRoute(route)
const resolvedRuntime = config.runtime ?? config.config?.runtime let resolvedRuntime = config.runtime ?? config.config?.runtime
if (isProxyFile(page) && resolvedRuntime) {
const relativePath = relative(process.cwd(), pageFilePath)
const resolvedPath = relativePath.startsWith('.')
? relativePath
: `./${relativePath}`
const message = `Route segment config is not allowed in Proxy file at "${resolvedPath}". Proxy always runs on Node.js runtime. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
if (isDev) {
// errorOnce as proxy/middleware runs per request including multiple
// internal _next/ routes and spams logs.
Log.errorOnce(message)
resolvedRuntime = SERVER_RUNTIME.nodejs
} else {
throw new Error(message)
}
}
if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) { if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge(isAnAPIRoute ? page! : null) warnAboutExperimentalEdge(isAnAPIRoute ? page! : null)
} }
if (resolvedRuntime === SERVER_RUNTIME.edge && page && !isAnAPIRoute) { if (
!isProxyFile(page) &&
resolvedRuntime === SERVER_RUNTIME.edge &&
page &&
!isAnAPIRoute
) {
const message = `Page ${page} provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.` const message = `Page ${page} provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`
if (isDev) { if (isDev) {
Log.error(message) Log.error(message)
......
...@@ -20,8 +20,6 @@ import { ...@@ -20,8 +20,6 @@ import {
APP_DIR_ALIAS, APP_DIR_ALIAS,
WEBPACK_LAYERS, WEBPACK_LAYERS,
INSTRUMENTATION_HOOK_FILENAME, INSTRUMENTATION_HOOK_FILENAME,
PROXY_FILENAME,
MIDDLEWARE_FILENAME,
} from '../lib/constants' } from '../lib/constants'
import { isAPIRoute } from '../lib/is-api-route' import { isAPIRoute } from '../lib/is-api-route'
import { isEdgeRuntime } from '../lib/is-edge-runtime' import { isEdgeRuntime } from '../lib/is-edge-runtime'
...@@ -43,6 +41,7 @@ import type { __ApiPreviewProps } from '../server/api-utils' ...@@ -43,6 +41,7 @@ import type { __ApiPreviewProps } from '../server/api-utils'
import { import {
isMiddlewareFile, isMiddlewareFile,
isMiddlewareFilename, isMiddlewareFilename,
isProxyFile,
isInstrumentationHookFile, isInstrumentationHookFile,
isInstrumentationHookFilename, isInstrumentationHookFilename,
} from './utils' } from './utils'
...@@ -573,7 +572,7 @@ export interface CreateEntrypointsParams { ...@@ -573,7 +572,7 @@ export interface CreateEntrypointsParams {
buildId: string buildId: string
config: NextConfigComplete config: NextConfigComplete
envFiles: LoadedEnvFiles envFiles: LoadedEnvFiles
isDev?: boolean isDev: boolean
pages: MappedPages pages: MappedPages
pagesDir?: string pagesDir?: string
previewMode: __ApiPreviewProps previewMode: __ApiPreviewProps
...@@ -642,6 +641,7 @@ export function getEdgeServerEntry(opts: { ...@@ -642,6 +641,7 @@ export function getEdgeServerEntry(opts: {
return { return {
import: `next-middleware-loader?${stringify(loaderParams)}!`, import: `next-middleware-loader?${stringify(loaderParams)}!`,
layer: WEBPACK_LAYERS.middleware, layer: WEBPACK_LAYERS.middleware,
filename: opts.isDev ? 'middleware.js' : undefined,
} }
} }
...@@ -764,6 +764,11 @@ export function runDependingOnPageType<T>(params: { ...@@ -764,6 +764,11 @@ export function runDependingOnPageType<T>(params: {
return return
} }
if (isProxyFile(params.page)) {
params.onServer()
return
}
if (isMiddlewareFile(params.page)) { if (isMiddlewareFile(params.page)) {
if (params.pageRuntime === 'nodejs') { if (params.pageRuntime === 'nodejs') {
params.onServer() params.onServer()
...@@ -947,13 +952,7 @@ export async function createEntrypoints( ...@@ -947,13 +952,7 @@ export async function createEntrypoints(
isDev: false, isDev: false,
}) })
} else if (isMiddlewareFile(page)) { } else if (isMiddlewareFile(page)) {
server[ server[serverBundlePath.replace('src/', '')] = getEdgeServerEntry({
serverBundlePath
// proxy.js still uses middleware.js for bundle path for now.
// TODO: Revisit when we remove middleware.js.
.replace(PROXY_FILENAME, MIDDLEWARE_FILENAME)
.replace('src/', '')
] = getEdgeServerEntry({
...params, ...params,
rootDir, rootDir,
absolutePagePath: absolutePagePath, absolutePagePath: absolutePagePath,
...@@ -1028,12 +1027,7 @@ export async function createEntrypoints( ...@@ -1028,12 +1027,7 @@ export async function createEntrypoints(
: undefined, : undefined,
}).import }).import
} }
const edgeServerBundlePath = isMiddlewareFile(page) edgeServer[serverBundlePath] = getEdgeServerEntry({
? serverBundlePath
.replace(PROXY_FILENAME, MIDDLEWARE_FILENAME)
.replace('src/', '')
: serverBundlePath
edgeServer[edgeServerBundlePath] = getEdgeServerEntry({
...params, ...params,
rootDir, rootDir,
absolutePagePath: absolutePagePath, absolutePagePath: absolutePagePath,
......
...@@ -29,7 +29,7 @@ export async function getStaticInfoIncludingLayouts({ ...@@ -29,7 +29,7 @@ export async function getStaticInfoIncludingLayouts({
pageFilePath: string pageFilePath: string
appDir: string | undefined appDir: string | undefined
config: NextConfigComplete config: NextConfigComplete
isDev: boolean | undefined isDev: boolean
page: string page: string
}): Promise<PageStaticInfo> { }): Promise<PageStaticInfo> {
// TODO: sync types for pages: PAGE_TYPES, ROUTER_TYPE, 'app' | 'pages', etc. // TODO: sync types for pages: PAGE_TYPES, ROUTER_TYPE, 'app' | 'pages', etc.
......
...@@ -139,6 +139,7 @@ import { ...@@ -139,6 +139,7 @@ import {
isAppBuiltinPage, isAppBuiltinPage,
collectRoutesUsingEdgeRuntime, collectRoutesUsingEdgeRuntime,
collectMeta, collectMeta,
isProxyFile,
} from './utils' } from './utils'
import type { PageInfo, PageInfos } from './utils' import type { PageInfo, PageInfos } from './utils'
import type { FallbackRouteParam, PrerenderedRoute } from './static-paths/types' import type { FallbackRouteParam, PrerenderedRoute } from './static-paths/types'
...@@ -1214,13 +1215,7 @@ export default async function build( ...@@ -1214,13 +1215,7 @@ export default async function build(
for (const rootPath of rootPaths) { for (const rootPath of rootPaths) {
const { name: fileBaseName, dir: fileDir } = path.parse(rootPath) const { name: fileBaseName, dir: fileDir } = path.parse(rootPath)
const isAtConventionLevel = const isAtConventionLevel = fileDir === '/' || fileDir === '/src'
fileDir === '/' ||
fileDir === '/src' ||
// rootPaths are currently relative paths from the root directory.
// Add safety check here for unexpected future changes.
fileDir === dir ||
fileDir === path.join(dir, 'src')
if (isAtConventionLevel && fileBaseName === MIDDLEWARE_FILENAME) { if (isAtConventionLevel && fileBaseName === MIDDLEWARE_FILENAME) {
middlewareFilePath = rootPath middlewareFilePath = rootPath
...@@ -2615,12 +2610,15 @@ export default async function build( ...@@ -2615,12 +2610,15 @@ export default async function build(
return serverFilesManifest return serverFilesManifest
}) })
const middlewareFile = rootPaths.find( const middlewareFile = proxyFilePath || middlewareFilePath
(p) => p.includes(MIDDLEWARE_FILENAME) || p.includes(PROXY_FILENAME)
)
let hasNodeMiddleware = false let hasNodeMiddleware = false
if (middlewareFile) { if (middlewareFile) {
// Is format of `(/src)/(proxy|middleware).<ext>`, so split by
// "." and get the first part, regard rest of the extensions
// to match the `page` value format.
const page = middlewareFile.split('.')[0]
const staticInfo = await getStaticInfoIncludingLayouts({ const staticInfo = await getStaticInfoIncludingLayouts({
isInsideAppDir: false, isInsideAppDir: false,
pageFilePath: path.join(dir, middlewareFile), pageFilePath: path.join(dir, middlewareFile),
...@@ -2628,17 +2626,17 @@ export default async function build( ...@@ -2628,17 +2626,17 @@ export default async function build(
appDir, appDir,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
isDev: false, isDev: false,
page: 'middleware', page,
}) })
if (staticInfo.hadUnsupportedValue) { if (staticInfo.hadUnsupportedValue) {
errorFromUnsupportedSegmentConfig() errorFromUnsupportedSegmentConfig()
} }
if (staticInfo.runtime === 'nodejs') { if (staticInfo.runtime === 'nodejs' || isProxyFile(page)) {
hasNodeMiddleware = true hasNodeMiddleware = true
functionsConfigManifest.functions['/_middleware'] = { functionsConfigManifest.functions['/_middleware'] = {
runtime: staticInfo.runtime, runtime: 'nodejs',
matchers: staticInfo.middleware?.matchers ?? [ matchers: staticInfo.middleware?.matchers ?? [
{ {
regexp: '^.*$', regexp: '^.*$',
...@@ -4154,6 +4152,17 @@ export default async function build( ...@@ -4154,6 +4152,17 @@ export default async function build(
buildTracesSpinner = undefined buildTracesSpinner = undefined
} }
if (proxyFilePath && bundler !== Bundler.Turbopack) {
await fs.rename(
path.join(distDir, SERVER_DIRECTORY, 'proxy.js'),
path.join(distDir, SERVER_DIRECTORY, 'middleware.js')
)
await fs.rename(
path.join(distDir, SERVER_DIRECTORY, 'proxy.js.nft.json'),
path.join(distDir, SERVER_DIRECTORY, 'middleware.js.nft.json')
)
}
if (isCompileMode) { if (isCompileMode) {
Log.info( Log.info(
`Build ran with "compile" mode, to finalize the build run either "generate" or "generate-env" mode as well` `Build ran with "compile" mode, to finalize the build run either "generate" or "generate-env" mode as well`
......
...@@ -85,3 +85,12 @@ export function warnOnce(...message: any[]) { ...@@ -85,3 +85,12 @@ export function warnOnce(...message: any[]) {
warn(...message) warn(...message)
} }
} }
const errorOnceCache = new LRUCache<string>(10_000, (value) => value.length)
export function errorOnce(...message: any[]) {
const key = message.join(' ')
if (!errorOnceCache.has(key)) {
errorOnceCache.set(key, key)
error(...message)
}
}
...@@ -11,33 +11,23 @@ import { isNextRouterError } from '../../client/components/is-next-router-error' ...@@ -11,33 +11,23 @@ import { isNextRouterError } from '../../client/components/is-next-router-error'
const mod = { ..._mod } const mod = { ..._mod }
const page = 'VAR_DEFINITION_PAGE' const page: string = 'VAR_DEFINITION_PAGE'
// Turbopack does not add a `./` prefix to the relative file path, but Webpack does.
const relativeFilePath = 'VAR_MODULE_RELATIVE_PATH'
// @ts-expect-error `page` will be replaced during build
const isProxy = page === '/proxy' || page === '/src/proxy' const isProxy = page === '/proxy' || page === '/src/proxy'
const handler = (isProxy ? mod.proxy : mod.middleware) || mod.default const handler = (isProxy ? mod.proxy : mod.middleware) || mod.default
if (typeof handler !== 'function') { class ProxyMissingExportError extends Error {
const fileName = isProxy ? 'proxy' : 'middleware' constructor(message: string) {
// Webpack starts the path with "." as relative, but Turbopack does not. super(message)
const resolvedRelativeFilePath = relativeFilePath.startsWith('.') // Stack isn't useful here, remove it considering it spams logs during development.
? relativeFilePath this.stack = ''
: `./${relativeFilePath}` }
}
throw new Error( // TODO: This spams logs during development. Find a better way to handle this.
`The file "${resolvedRelativeFilePath}" must export a function, either as a default export or as a named "${fileName}" export.\n` + // Removing this will spam "fn is not a function" logs which is worse.
`This function is what Next.js runs for every request handled by this ${fileName === 'proxy' ? 'proxy (previously called middleware)' : 'middleware'}.\n\n` + if (typeof handler !== 'function') {
`Why this happens:\n` + throw new ProxyMissingExportError(
(isProxy `The ${isProxy ? 'Proxy' : 'Middleware'} file "${page}" must export a function named \`${isProxy ? 'proxy' : 'middleware'}\` or a default function.`
? "- You are migrating from `middleware` to `proxy`, but haven't updated the exported function.\n"
: '') +
`- The file exists but doesn't export a function.\n` +
`- The export is not a function (e.g., an object or constant).\n` +
`- There's a syntax error preventing the export from being recognized.\n\n` +
`To fix it:\n` +
`- Ensure this file has either a default or "${fileName}" function export.\n\n` +
`Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
) )
} }
......
...@@ -1421,6 +1421,10 @@ export function isMiddlewareFile(file: string) { ...@@ -1421,6 +1421,10 @@ export function isMiddlewareFile(file: string) {
) )
} }
export function isProxyFile(file: string) {
return file === `/${PROXY_FILENAME}` || file === `/src/${PROXY_FILENAME}`
}
export function isInstrumentationHookFile(file: string) { export function isInstrumentationHookFile(file: string) {
return ( return (
file === `/${INSTRUMENTATION_HOOK_FILENAME}` || file === `/${INSTRUMENTATION_HOOK_FILENAME}` ||
......
...@@ -70,8 +70,5 @@ export default async function middlewareLoader(this: any) { ...@@ -70,8 +70,5 @@ export default async function middlewareLoader(this: any) {
return await loadEntrypoint('middleware', { return await loadEntrypoint('middleware', {
VAR_USERLAND: pagePath, VAR_USERLAND: pagePath,
VAR_DEFINITION_PAGE: page, VAR_DEFINITION_PAGE: page,
// Turbopack sets `VAR_USERLAND` to `INNER_MIDDLEWARE_MODULE`, so use
// `VAR_MODULE_RELATIVE_PATH` for error messages.
VAR_MODULE_RELATIVE_PATH: pagePath,
}) })
} }
...@@ -89,6 +89,7 @@ import { ...@@ -89,6 +89,7 @@ import {
processIssues, processIssues,
renderStyledStringToErrorAnsi, renderStyledStringToErrorAnsi,
type EntryIssuesMap, type EntryIssuesMap,
type IssuesMap,
type TopLevelIssuesMap, type TopLevelIssuesMap,
} from '../../shared/lib/turbopack/utils' } from '../../shared/lib/turbopack/utils'
import { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware' import { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware'
...@@ -1432,28 +1433,36 @@ export async function createHotReloaderTurbopack( ...@@ -1432,28 +1433,36 @@ export async function createHotReloaderTurbopack(
case 'end': { case 'end': {
sendEnqueuedMessages() sendEnqueuedMessages()
function addToErrorsMap(
errorsMap: Map<string, CompilationError>,
issueMap: IssuesMap
) {
for (const [key, issue] of issueMap) {
if (issue.severity === 'warning') continue
if (errorsMap.has(key)) continue
const message = formatIssue(issue)
errorsMap.set(key, {
message,
details: issue.detail
? renderStyledStringToErrorAnsi(issue.detail)
: undefined,
})
}
}
function addErrors( function addErrors(
errorsMap: Map<string, CompilationError>, errorsMap: Map<string, CompilationError>,
issues: EntryIssuesMap issues: EntryIssuesMap
) { ) {
for (const issueMap of issues.values()) { for (const issueMap of issues.values()) {
for (const [key, issue] of issueMap) { addToErrorsMap(errorsMap, issueMap)
if (issue.severity === 'warning') continue
if (errorsMap.has(key)) continue
const message = formatIssue(issue)
errorsMap.set(key, {
message,
details: issue.detail
? renderStyledStringToErrorAnsi(issue.detail)
: undefined,
})
}
} }
} }
const errors = new Map<string, CompilationError>() const errors = new Map<string, CompilationError>()
addToErrorsMap(errors, currentTopLevelIssues)
addErrors(errors, currentEntryIssues) addErrors(errors, currentEntryIssues)
for (const client of [ for (const client of [
......
...@@ -1574,6 +1574,10 @@ export default class NextNodeServer extends BaseServer< ...@@ -1574,6 +1574,10 @@ export default class NextNodeServer extends BaseServer<
functionsConfig?.functions?.['/_middleware'] functionsConfig?.functions?.['/_middleware']
) { ) {
// if used with top level await, this will be a promise // if used with top level await, this will be a promise
// Try loading middleware.js first, then proxy.js. Instead
// of mapping proxy to middleware as the entry, just fallback
// to proxy.
// TODO: Remove this once we handle as the single entrypoint.
return require( return require(
join( join(
/* turbopackIgnore: true */ this.distDir, /* turbopackIgnore: true */ this.distDir,
...@@ -1736,7 +1740,10 @@ export default class NextNodeServer extends BaseServer< ...@@ -1736,7 +1740,10 @@ export default class NextNodeServer extends BaseServer<
try { try {
result = await adapterFn({ result = await adapterFn({
handler: middlewareModule.middleware || middlewareModule, handler:
middlewareModule.proxy ||
middlewareModule.middleware ||
middlewareModule,
request: { request: {
...requestData, ...requestData,
body: hasRequestBody body: hasRequestBody
......
...@@ -117,7 +117,9 @@ describe('app-dir with proxy', () => { ...@@ -117,7 +117,9 @@ describe('app-dir with proxy', () => {
expect(res.headers.get('x-middleware-request-x-from-client3')).toBeNull() expect(res.headers.get('x-middleware-request-x-from-client3')).toBeNull()
}) })
it(`Supports draft mode`, async () => { // Cannot set draftMode in nodejs runtime
// TODO: Investigate https://github.com/vercel/next.js/pull/85174
it.skip(`Supports draft mode`, async () => {
const res = await next.fetch(`${path}?draft=true`) const res = await next.fetch(`${path}?draft=true`)
const headers: string = res.headers.get('set-cookie') || '' const headers: string = res.headers.get('set-cookie') || ''
const bypassCookie = headers const bypassCookie = headers
......
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { headers as nextHeaders, draftMode } from 'next/headers' import { headers as nextHeaders } from 'next/headers'
/** /**
* @param {import('next/server').NextRequest} request * @param {import('next/server').NextRequest} request
...@@ -20,9 +20,11 @@ export async function proxy(request) { ...@@ -20,9 +20,11 @@ export async function proxy(request) {
throw new Error('Expected headers from client to match') throw new Error('Expected headers from client to match')
} }
if (request.nextUrl.searchParams.get('draft')) { // Cannot set draftMode in nodejs runtime
;(await draftMode()).enable() // TODO: Investigate https://github.com/vercel/next.js/pull/85174
} // if (request.nextUrl.searchParams.get('draft')) {
// ;(await draftMode()).enable()
// }
const removeHeaders = request.nextUrl.searchParams.get('remove-headers') const removeHeaders = request.nextUrl.searchParams.get('remove-headers')
if (removeHeaders) { if (removeHeaders) {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('proxy-runtime-nodejs', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should use nodejs runtime for proxy by default', async () => {
const browser = await next.browser('/foo')
expect(await browser.elementByCss('p').text()).toBe('hello world')
})
})
import { NextRequest, NextResponse } from 'next/server'
// Will not work in edge runtime
import { join } from 'path/posix'
export function proxy(request: NextRequest) {
if (request.nextUrl.pathname === join('/', 'foo')) {
return NextResponse.redirect(new URL('/', request.url))
}
return NextResponse.next()
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import stripAnsi from 'strip-ansi'
describe('proxy-runtime', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
})
if (skipped) {
return
}
it('should error when proxy file has runtime config export', async () => {
let cliOutput: string
if (isNextDev) {
await next.start().catch(() => {})
// Use .catch() because Turbopack errors during compile and exits before runtime.
await next.browser('/').catch(() => {})
cliOutput = next.cliOutput
} else {
cliOutput = (await next.build()).cliOutput
}
// TODO: Investigate why in dev-turbo, the error is shown in the browser console, not CLI output.
if (process.env.IS_TURBOPACK_TEST && !isNextDev) {
expect(stripAnsi(cliOutput)).toContain(`proxy.ts:3:14
Next.js can't recognize the exported \`config\` field in route. Proxy does not support Edge runtime.
1 | export default function () {}
2 |
> 3 | export const config = { runtime: 'edge' }
| ^^^^^^
4 |
The exported configuration object in a source file needs to have a very specific format from which some properties can be statically parsed at compiled-time.`)
} else {
expect(cliOutput).toContain(
`Route segment config is not allowed in Proxy file at "./proxy.ts". Proxy always runs on Node.js runtime. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
)
}
await next.stop()
})
})
export default function () {}
export const config = { runtime: 'edge' }
import { NextProxy, NextResponse, URLPattern, ProxyConfig } from 'next/server' import { NextProxy, NextResponse, ProxyConfig } from 'next/server'
export const proxy: NextProxy = function (request) { export const proxy: NextProxy = function (request) {
const pattern = new URLPattern({
pathname: '/:path',
})
console.log(pattern.test(request.nextUrl.pathname))
if (request.nextUrl.pathname === '/static') { if (request.nextUrl.pathname === '/static') {
return new NextResponse(null, { return new NextResponse(null, {
headers: { headers: {
......
...@@ -16,6 +16,7 @@ describe('parse page static info', () => { ...@@ -16,6 +16,7 @@ describe('parse page static info', () => {
pageFilePath: join(fixtureDir, 'page-runtime/nodejs-ssr.js'), pageFilePath: join(fixtureDir, 'page-runtime/nodejs-ssr.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: PAGE_TYPES.PAGES, pageType: PAGE_TYPES.PAGES,
isDev: false,
}) })
expect(runtime).toBe('nodejs') expect(runtime).toBe('nodejs')
expect(getServerSideProps).toBe(true) expect(getServerSideProps).toBe(true)
...@@ -29,6 +30,7 @@ describe('parse page static info', () => { ...@@ -29,6 +30,7 @@ describe('parse page static info', () => {
pageFilePath: join(fixtureDir, 'page-runtime/nodejs.js'), pageFilePath: join(fixtureDir, 'page-runtime/nodejs.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: PAGE_TYPES.PAGES, pageType: PAGE_TYPES.PAGES,
isDev: false,
}) })
expect(runtime).toBe('nodejs') expect(runtime).toBe('nodejs')
expect(getServerSideProps).toBe(false) expect(getServerSideProps).toBe(false)
...@@ -41,6 +43,7 @@ describe('parse page static info', () => { ...@@ -41,6 +43,7 @@ describe('parse page static info', () => {
pageFilePath: join(fixtureDir, 'page-runtime/edge.js'), pageFilePath: join(fixtureDir, 'page-runtime/edge.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: PAGE_TYPES.PAGES, pageType: PAGE_TYPES.PAGES,
isDev: false,
}) })
expect(runtime).toBe('experimental-edge') expect(runtime).toBe('experimental-edge')
}) })
...@@ -51,6 +54,7 @@ describe('parse page static info', () => { ...@@ -51,6 +54,7 @@ describe('parse page static info', () => {
pageFilePath: join(fixtureDir, 'page-runtime/static.js'), pageFilePath: join(fixtureDir, 'page-runtime/static.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: PAGE_TYPES.PAGES, pageType: PAGE_TYPES.PAGES,
isDev: false,
}) })
expect(runtime).toBe(undefined) expect(runtime).toBe(undefined)
}) })
...@@ -62,6 +66,7 @@ describe('parse page static info', () => { ...@@ -62,6 +66,7 @@ describe('parse page static info', () => {
pageFilePath: join(fixtureDir, 'page-runtime/ssr-variable-gssp.js'), pageFilePath: join(fixtureDir, 'page-runtime/ssr-variable-gssp.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: PAGE_TYPES.PAGES, pageType: PAGE_TYPES.PAGES,
isDev: false,
} }
) )
expect(getStaticProps).toBe(false) expect(getStaticProps).toBe(false)
......
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