Unverified Commit d540fbd3 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Deprecate Middleware API and add Proxy API (#84764)

Following up on https://github.com/vercel/next.js/pull/84119, this PR
deprecated the user-facing middleware API and added a replacement Proxy
API.

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 17c99ca4
...@@ -1156,8 +1156,8 @@ impl Project { ...@@ -1156,8 +1156,8 @@ impl Project {
let config = self.next_config(); let config = self.next_config();
emit_event( emit_event(
"skipMiddlewareUrlNormalize", "skipProxyUrlNormalize",
*config.skip_middleware_url_normalize().await?, *config.skip_proxy_url_normalize().await?,
); );
emit_event( emit_event(
......
...@@ -69,7 +69,7 @@ ...@@ -69,7 +69,7 @@
"clientRouterFilter": true, "clientRouterFilter": true,
"clientRouterFilterRedirects": false, "clientRouterFilterRedirects": false,
"fetchCacheKeyPrefix": "", "fetchCacheKeyPrefix": "",
"middlewarePrefetch": "flexible", "proxyPrefetch": "flexible",
"optimisticClientCache": true, "optimisticClientCache": true,
"manualClientBasePath": false, "manualClientBasePath": false,
"cpus": 2, "cpus": 2,
......
...@@ -102,7 +102,7 @@ pub struct NextConfig { ...@@ -102,7 +102,7 @@ pub struct NextConfig {
trailing_slash: Option<bool>, trailing_slash: Option<bool>,
asset_prefix: Option<RcStr>, asset_prefix: Option<RcStr>,
base_path: Option<RcStr>, base_path: Option<RcStr>,
skip_middleware_url_normalize: Option<bool>, skip_proxy_url_normalize: Option<bool>,
skip_trailing_slash_redirect: Option<bool>, skip_trailing_slash_redirect: Option<bool>,
i18n: Option<I18NConfig>, i18n: Option<I18NConfig>,
cross_origin: Option<CrossOriginConfig>, cross_origin: Option<CrossOriginConfig>,
...@@ -1660,8 +1660,8 @@ impl NextConfig { ...@@ -1660,8 +1660,8 @@ impl NextConfig {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn skip_middleware_url_normalize(&self) -> Vc<bool> { pub fn skip_proxy_url_normalize(&self) -> Vc<bool> {
Vc::cell(self.skip_middleware_url_normalize.unwrap_or(false)) Vc::cell(self.skip_proxy_url_normalize.unwrap_or(false))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -572,7 +572,7 @@ async fn parse_config_value( ...@@ -572,7 +572,7 @@ async fn parse_config_value(
) -> Result<()> { ) -> Result<()> {
let get_value = || { let get_value = || {
let init = init.as_deref(); let init = init.as_deref();
// Unwrap `export const config = { .. } satisfies MiddlewareConfig`, usually this is already // Unwrap `export const config = { .. } satisfies ProxyConfig`, usually this is already
// transpiled away, but we are looking at the original source here. // transpiled away, but we are looking at the original source here.
let init = if let Some(Expr::TsSatisfies(TsSatisfiesExpr { expr, .. })) = init { let init = if let Some(Expr::TsSatisfies(TsSatisfiesExpr { expr, .. })) = init {
Some(&**expr) Some(&**expr)
......
...@@ -874,5 +874,9 @@ ...@@ -874,5 +874,9 @@
"873": "Invalid profile provided \"%s\" must be configured under cacheLife in next.config or be \"max\"", "873": "Invalid profile provided \"%s\" must be configured under cacheLife in next.config or be \"max\"",
"874": "Expected not to install Node.js global behaviors in the edge runtime.", "874": "Expected not to install Node.js global behaviors in the edge runtime.",
"875": "`pipelineInSequentialTasks` should not be called in edge runtime.", "875": "`pipelineInSequentialTasks` should not be called in edge runtime.",
"876": "dynamicInDevStagedRendering should only be used in development mode and when Cache Components is enabled." "876": "dynamicInDevStagedRendering should only be used in development mode and when Cache Components is enabled.",
"877": "Config options `experimental.externalProxyRewritesResolve` and `experimental.externalMiddlewareRewritesResolve` cannot be set at the same time. Please use `experimental.externalProxyRewritesResolve` instead.",
"878": "Config options `skipProxyUrlNormalize` and `skipMiddlewareUrlNormalize` cannot be set at the same time. Please use `skipProxyUrlNormalize` instead.",
"879": "Config options `experimental.proxyClientMaxBodySize` and `experimental.middlewareClientMaxBodySize` cannot be set at the same time. Please use `experimental.proxyClientMaxBodySize` instead.",
"880": "Config options `experimental.proxyPrefetch` and `experimental.middlewarePrefetch` cannot be set at the same time. Please use `experimental.proxyPrefetch` instead."
} }
...@@ -7,7 +7,12 @@ declare global { ...@@ -7,7 +7,12 @@ declare global {
export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event' export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event'
export { NextRequest } from 'next/dist/server/web/spec-extension/request' export { NextRequest } from 'next/dist/server/web/spec-extension/request'
export { NextResponse } from 'next/dist/server/web/spec-extension/response' export { NextResponse } from 'next/dist/server/web/spec-extension/response'
export { NextMiddleware, MiddlewareConfig } from 'next/dist/server/web/types' export {
NextMiddleware,
MiddlewareConfig,
NextProxy,
ProxyConfig,
} from 'next/dist/server/web/types'
export { userAgentFromString } from 'next/dist/server/web/spec-extension/user-agent' export { userAgentFromString } from 'next/dist/server/web/spec-extension/user-agent'
export { userAgent } from 'next/dist/server/web/spec-extension/user-agent' export { userAgent } from 'next/dist/server/web/spec-extension/user-agent'
export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url' export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url'
......
...@@ -47,7 +47,7 @@ export type MiddlewareMatcher = { ...@@ -47,7 +47,7 @@ export type MiddlewareMatcher = {
originalSource: string originalSource: string
} }
export type MiddlewareConfig = { export type ProxyConfig = {
/** /**
* The matcher for the middleware. Read more: [Next.js Docs: Middleware `matcher`](https://nextjs.org/docs/app/api-reference/file-conventions/middleware#matcher), * The matcher for the middleware. Read more: [Next.js Docs: Middleware `matcher`](https://nextjs.org/docs/app/api-reference/file-conventions/middleware#matcher),
* [Next.js Docs: Middleware matching paths](https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths) * [Next.js Docs: Middleware matching paths](https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths)
...@@ -74,7 +74,7 @@ export interface AppPageStaticInfo { ...@@ -74,7 +74,7 @@ export interface AppPageStaticInfo {
generateStaticParams?: boolean generateStaticParams?: boolean
generateSitemaps?: boolean generateSitemaps?: boolean
generateImageMetadata?: boolean generateImageMetadata?: boolean
middleware?: MiddlewareConfig middleware?: ProxyConfig
config: Omit<AppSegmentConfig, 'runtime' | 'maxDuration'> | undefined config: Omit<AppSegmentConfig, 'runtime' | 'maxDuration'> | undefined
runtime: AppSegmentConfig['runtime'] | undefined runtime: AppSegmentConfig['runtime'] | undefined
preferredRegion: AppSegmentConfig['preferredRegion'] | undefined preferredRegion: AppSegmentConfig['preferredRegion'] | undefined
...@@ -90,7 +90,7 @@ export interface PagesPageStaticInfo { ...@@ -90,7 +90,7 @@ export interface PagesPageStaticInfo {
generateStaticParams?: boolean generateStaticParams?: boolean
generateSitemaps?: boolean generateSitemaps?: boolean
generateImageMetadata?: boolean generateImageMetadata?: boolean
middleware?: MiddlewareConfig middleware?: ProxyConfig
config: config:
| (Omit<PagesSegmentConfig, 'runtime' | 'config' | 'maxDuration'> & { | (Omit<PagesSegmentConfig, 'runtime' | 'config' | 'maxDuration'> & {
config?: Omit<PagesSegmentConfigConfig, 'runtime' | 'maxDuration'> config?: Omit<PagesSegmentConfigConfig, 'runtime' | 'maxDuration'>
...@@ -372,7 +372,7 @@ function parseMiddlewareConfig( ...@@ -372,7 +372,7 @@ function parseMiddlewareConfig(
page: string, page: string,
rawConfig: unknown, rawConfig: unknown,
nextConfig: NextConfig nextConfig: NextConfig
): MiddlewareConfig { ): ProxyConfig {
// If there's no config to parse, then return nothing. // If there's no config to parse, then return nothing.
if (typeof rawConfig !== 'object' || !rawConfig) return {} if (typeof rawConfig !== 'object' || !rawConfig) return {}
...@@ -386,7 +386,7 @@ function parseMiddlewareConfig( ...@@ -386,7 +386,7 @@ function parseMiddlewareConfig(
process.exit(1) process.exit(1)
} }
const config: MiddlewareConfig = {} const config: ProxyConfig = {}
if (input.data.matcher) { if (input.data.matcher) {
config.matchers = getMiddlewareMatchers(input.data.matcher, nextConfig) config.matchers = getMiddlewareMatchers(input.data.matcher, nextConfig)
......
...@@ -214,7 +214,7 @@ export function getDefineEnv({ ...@@ -214,7 +214,7 @@ export function getDefineEnv({
'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE': 'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':
config.experimental.optimisticClientCache ?? true, config.experimental.optimisticClientCache ?? true,
'process.env.__NEXT_MIDDLEWARE_PREFETCH': 'process.env.__NEXT_MIDDLEWARE_PREFETCH':
config.experimental.middlewarePrefetch ?? 'flexible', config.experimental.proxyPrefetch ?? 'flexible',
'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin, 'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,
'process.browser': isClient, 'process.browser': isClient,
'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false, 'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false,
...@@ -263,9 +263,9 @@ export function getDefineEnv({ ...@@ -263,9 +263,9 @@ export function getDefineEnv({
'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false, 'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false,
'process.env.__NEXT_I18N_CONFIG': config.i18n || '', 'process.env.__NEXT_I18N_CONFIG': config.i18n || '',
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE': 'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':
config.skipMiddlewareUrlNormalize, config.skipProxyUrlNormalize,
'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE': 'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':
config.experimental.externalMiddlewareRewritesResolve ?? false, config.experimental.externalProxyRewritesResolve ?? false,
'process.env.__NEXT_MANUAL_TRAILING_SLASH': 'process.env.__NEXT_MANUAL_TRAILING_SLASH':
config.skipTrailingSlashRedirect, config.skipTrailingSlashRedirect,
'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION': 'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION':
......
...@@ -5,7 +5,7 @@ import type { EdgeAppRouteLoaderQuery } from './webpack/loaders/next-edge-app-ro ...@@ -5,7 +5,7 @@ import type { EdgeAppRouteLoaderQuery } from './webpack/loaders/next-edge-app-ro
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type { import type {
MiddlewareConfig, ProxyConfig,
MiddlewareMatcher, MiddlewareMatcher,
PageStaticInfo, PageStaticInfo,
} from './analysis/get-page-static-info' } from './analysis/get-page-static-info'
...@@ -595,12 +595,12 @@ export function getEdgeServerEntry(opts: { ...@@ -595,12 +595,12 @@ export function getEdgeServerEntry(opts: {
isServerComponent: boolean isServerComponent: boolean
page: string page: string
pages: MappedPages pages: MappedPages
middleware?: Partial<MiddlewareConfig> middleware?: Partial<ProxyConfig>
pagesType: PAGE_TYPES pagesType: PAGE_TYPES
appDirLoader?: string appDirLoader?: string
hasInstrumentationHook?: boolean hasInstrumentationHook?: boolean
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
middlewareConfig?: MiddlewareConfig middlewareConfig?: ProxyConfig
}) { }) {
if ( if (
opts.pagesType === 'app' && opts.pagesType === 'app' &&
......
...@@ -485,7 +485,7 @@ export type RoutesManifest = { ...@@ -485,7 +485,7 @@ export type RoutesManifest = {
pathHeader: typeof NEXT_REWRITTEN_PATH_HEADER pathHeader: typeof NEXT_REWRITTEN_PATH_HEADER
queryHeader: typeof NEXT_REWRITTEN_QUERY_HEADER queryHeader: typeof NEXT_REWRITTEN_QUERY_HEADER
} }
skipMiddlewareUrlNormalize?: boolean skipProxyUrlNormalize?: boolean
caseSensitive?: boolean caseSensitive?: boolean
/** /**
* Configuration related to Partial Prerendering. * Configuration related to Partial Prerendering.
...@@ -1605,7 +1605,7 @@ export default async function build( ...@@ -1605,7 +1605,7 @@ export default async function build(
pathHeader: NEXT_REWRITTEN_PATH_HEADER, pathHeader: NEXT_REWRITTEN_PATH_HEADER,
queryHeader: NEXT_REWRITTEN_QUERY_HEADER, queryHeader: NEXT_REWRITTEN_QUERY_HEADER,
}, },
skipMiddlewareUrlNormalize: config.skipMiddlewareUrlNormalize, skipProxyUrlNormalize: config.skipProxyUrlNormalize,
ppr: isAppPPREnabled ppr: isAppPPREnabled
? { ? {
chain: { chain: {
......
...@@ -952,7 +952,7 @@ export default async function getBaseWebpackConfig( ...@@ -952,7 +952,7 @@ export default async function getBaseWebpackConfig(
['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource], ['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource],
['swcEmotion', !!config.compiler?.emotion], ['swcEmotion', !!config.compiler?.emotion],
['transpilePackages', !!config.transpilePackages], ['transpilePackages', !!config.transpilePackages],
['skipMiddlewareUrlNormalize', !!config.skipMiddlewareUrlNormalize], ['skipProxyUrlNormalize', !!config.skipProxyUrlNormalize],
['skipTrailingSlashRedirect', !!config.skipTrailingSlashRedirect], ['skipTrailingSlashRedirect', !!config.skipTrailingSlashRedirect],
['modularizeImports', !!config.modularizeImports], ['modularizeImports', !!config.modularizeImports],
// If esmExternals is not same as default value, it represents customized usage // If esmExternals is not same as default value, it represents customized usage
......
import type { import type {
MiddlewareConfig, ProxyConfig,
MiddlewareMatcher, MiddlewareMatcher,
RSCModuleType, RSCModuleType,
} from '../../analysis/get-page-static-info' } from '../../analysis/get-page-static-info'
...@@ -39,7 +39,7 @@ export interface RouteMeta { ...@@ -39,7 +39,7 @@ export interface RouteMeta {
page: string page: string
absolutePagePath: string absolutePagePath: string
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
middlewareConfig: MiddlewareConfig middlewareConfig: ProxyConfig
// references to other modules that this route needs // references to other modules that this route needs
// e.g. related routes, not-found routes, etc // e.g. related routes, not-found routes, etc
relatedModules?: string[] relatedModules?: string[]
......
...@@ -24,7 +24,7 @@ import { promises as fs } from 'fs' ...@@ -24,7 +24,7 @@ import { promises as fs } from 'fs'
import { isAppRouteRoute } from '../../../../lib/is-app-route-route' import { isAppRouteRoute } from '../../../../lib/is-app-route-route'
import type { NextConfig } from '../../../../server/config-shared' import type { NextConfig } from '../../../../server/config-shared'
import { AppPathnameNormalizer } from '../../../../server/normalizers/built/app/app-pathname-normalizer' import { AppPathnameNormalizer } from '../../../../server/normalizers/built/app/app-pathname-normalizer'
import type { MiddlewareConfig } from '../../../analysis/get-page-static-info' import type { ProxyConfig } from '../../../analysis/get-page-static-info'
import { isAppBuiltinPage } from '../../../utils' import { isAppBuiltinPage } from '../../../utils'
import { loadEntrypoint } from '../../../load-entrypoint' import { loadEntrypoint } from '../../../load-entrypoint'
import { import {
...@@ -644,7 +644,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -644,7 +644,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
const collectedDeclarations: [string, string][] = [] const collectedDeclarations: [string, string][] = []
const page = name.replace(/^app/, '') const page = name.replace(/^app/, '')
const middlewareConfig: MiddlewareConfig = JSON.parse( const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
) )
buildInfo.route = { buildInfo.route = {
......
...@@ -2,7 +2,7 @@ import { getModuleBuildInfo } from '../get-module-build-info' ...@@ -2,7 +2,7 @@ import { getModuleBuildInfo } from '../get-module-build-info'
import { stringifyRequest } from '../../stringify-request' import { stringifyRequest } from '../../stringify-request'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
import type { MiddlewareConfig } from '../../../analysis/get-page-static-info' import type { ProxyConfig } from '../../../analysis/get-page-static-info'
import { loadEntrypoint } from '../../../load-entrypoint' import { loadEntrypoint } from '../../../load-entrypoint'
import { isMetadataRoute } from '../../../../lib/metadata/is-metadata-route' import { isMetadataRoute } from '../../../../lib/metadata/is-metadata-route'
...@@ -29,7 +29,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -29,7 +29,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
} = this.getOptions() } = this.getOptions()
const appDirLoader = Buffer.from(appDirLoaderBase64, 'base64').toString() const appDirLoader = Buffer.from(appDirLoaderBase64, 'base64').toString()
const middlewareConfig: MiddlewareConfig = JSON.parse( const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
) )
......
import type webpack from 'webpack' import type webpack from 'webpack'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request' import { stringifyRequest } from '../stringify-request'
import type { MiddlewareConfig } from '../../analysis/get-page-static-info' import type { ProxyConfig } from '../../analysis/get-page-static-info'
export type EdgeFunctionLoaderOptions = { export type EdgeFunctionLoaderOptions = {
absolutePagePath: string absolutePagePath: string
...@@ -22,7 +22,7 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade ...@@ -22,7 +22,7 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade
}: EdgeFunctionLoaderOptions = this.getOptions() }: EdgeFunctionLoaderOptions = this.getOptions()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module as any) const buildInfo = getModuleBuildInfo(this._module as any)
const middlewareConfig: MiddlewareConfig = JSON.parse( const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
) )
buildInfo.route = { buildInfo.route = {
......
import type webpack from 'webpack' import type webpack from 'webpack'
import type { SizeLimit } from '../../../../types' import type { SizeLimit } from '../../../../types'
import type { PagesRouteModuleOptions } from '../../../../server/route-modules/pages/module' import type { PagesRouteModuleOptions } from '../../../../server/route-modules/pages/module'
import type { MiddlewareConfig } from '../../../analysis/get-page-static-info' import type { ProxyConfig } from '../../../analysis/get-page-static-info'
import { getModuleBuildInfo } from '../get-module-build-info' import { getModuleBuildInfo } from '../get-module-build-info'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
...@@ -90,7 +90,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -90,7 +90,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
) )
} }
const middlewareConfig: MiddlewareConfig = JSON.parse( const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
) )
......
import type { import type {
MiddlewareConfig, ProxyConfig,
MiddlewareMatcher, MiddlewareMatcher,
} from '../../analysis/get-page-static-info' } from '../../analysis/get-page-static-info'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
...@@ -45,7 +45,7 @@ export default async function middlewareLoader(this: any) { ...@@ -45,7 +45,7 @@ export default async function middlewareLoader(this: any) {
absolutePagePath absolutePagePath
) )
const middlewareConfig: MiddlewareConfig = JSON.parse( const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
) )
const buildInfo = getModuleBuildInfo(this._module) const buildInfo = getModuleBuildInfo(this._module)
......
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type { MiddlewareConfig } from '../../../analysis/get-page-static-info' import type { ProxyConfig } from '../../../analysis/get-page-static-info'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { import {
...@@ -18,7 +18,7 @@ type RouteLoaderOptionsPagesAPIInput = { ...@@ -18,7 +18,7 @@ type RouteLoaderOptionsPagesAPIInput = {
page: string page: string
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
absolutePagePath: string absolutePagePath: string
middlewareConfig: MiddlewareConfig middlewareConfig: ProxyConfig
} }
type RouteLoaderOptionsPagesInput = { type RouteLoaderOptionsPagesInput = {
...@@ -27,7 +27,7 @@ type RouteLoaderOptionsPagesInput = { ...@@ -27,7 +27,7 @@ type RouteLoaderOptionsPagesInput = {
pages: MappedPages pages: MappedPages
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
absolutePagePath: string absolutePagePath: string
middlewareConfig: MiddlewareConfig middlewareConfig: ProxyConfig
} }
type RouteLoaderOptionsInput = type RouteLoaderOptionsInput =
...@@ -148,9 +148,7 @@ const loadPages = async ( ...@@ -148,9 +148,7 @@ const loadPages = async (
}: RouteLoaderPagesOptions, }: RouteLoaderPagesOptions,
buildInfo: ModuleBuildInfo buildInfo: ModuleBuildInfo
) => { ) => {
const middlewareConfig: MiddlewareConfig = decodeFromBase64( const middlewareConfig: ProxyConfig = decodeFromBase64(middlewareConfigBase64)
middlewareConfigBase64
)
// Attach build info to the module. // Attach build info to the module.
buildInfo.route = { buildInfo.route = {
...@@ -187,9 +185,7 @@ const loadPagesAPI = async ( ...@@ -187,9 +185,7 @@ const loadPagesAPI = async (
}: RouteLoaderPagesAPIOptions, }: RouteLoaderPagesAPIOptions,
buildInfo: ModuleBuildInfo buildInfo: ModuleBuildInfo
) => { ) => {
const middlewareConfig: MiddlewareConfig = decodeFromBase64( const middlewareConfig: ProxyConfig = decodeFromBase64(middlewareConfigBase64)
middlewareConfigBase64
)
// Attach build info to the module. // Attach build info to the module.
buildInfo.route = { buildInfo.route = {
......
...@@ -23,7 +23,7 @@ import { ...@@ -23,7 +23,7 @@ import {
INTERCEPTION_ROUTE_REWRITE_MANIFEST, INTERCEPTION_ROUTE_REWRITE_MANIFEST,
DYNAMIC_CSS_MANIFEST, DYNAMIC_CSS_MANIFEST,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import type { MiddlewareConfig } 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'
import { traceGlobals } from '../../../trace/shared' import { traceGlobals } from '../../../trace/shared'
import { EVENT_BUILD_FEATURE_USAGE } from '../../../telemetry/events' import { EVENT_BUILD_FEATURE_USAGE } from '../../../telemetry/events'
...@@ -294,7 +294,7 @@ function isBunModule(moduleName: string) { ...@@ -294,7 +294,7 @@ function isBunModule(moduleName: string) {
function isDynamicCodeEvaluationAllowed( function isDynamicCodeEvaluationAllowed(
fileName: string, fileName: string,
middlewareConfig?: MiddlewareConfig, middlewareConfig?: ProxyConfig,
rootDir?: string rootDir?: string
) { ) {
// Some packages are known to use `eval` but are safe to use in the Edge // Some packages are known to use `eval` but are safe to use in the Edge
......
...@@ -415,7 +415,7 @@ function createServerDefinitions() { ...@@ -415,7 +415,7 @@ function createServerDefinitions() {
export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event' export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event'
export { NextRequest } from 'next/dist/server/web/spec-extension/request' export { NextRequest } from 'next/dist/server/web/spec-extension/request'
export { NextResponse } from 'next/dist/server/web/spec-extension/response' export { NextResponse } from 'next/dist/server/web/spec-extension/response'
export { NextMiddleware, MiddlewareConfig } from 'next/dist/server/web/types' export { NextMiddleware, MiddlewareConfig, NextProxy, ProxyConfig } from 'next/dist/server/web/types'
export { userAgentFromString } from 'next/dist/server/web/spec-extension/user-agent' export { userAgentFromString } from 'next/dist/server/web/spec-extension/user-agent'
export { userAgent } from 'next/dist/server/web/spec-extension/user-agent' export { userAgent } from 'next/dist/server/web/spec-extension/user-agent'
export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url' export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url'
......
...@@ -43,7 +43,7 @@ export type Feature = ...@@ -43,7 +43,7 @@ export type Feature =
| `swc/target/${SWC_TARGET_TRIPLE}` | `swc/target/${SWC_TARGET_TRIPLE}`
| 'turbotrace' | 'turbotrace'
| 'transpilePackages' | 'transpilePackages'
| 'skipMiddlewareUrlNormalize' | 'skipProxyUrlNormalize'
| 'skipTrailingSlashRedirect' | 'skipTrailingSlashRedirect'
| 'modularizeImports' | 'modularizeImports'
| 'esmExternals' | 'esmExternals'
...@@ -101,7 +101,7 @@ const BUILD_FEATURES: Array<Feature> = [ ...@@ -101,7 +101,7 @@ const BUILD_FEATURES: Array<Feature> = [
'swc/target/aarch64-pc-windows-msvc', 'swc/target/aarch64-pc-windows-msvc',
'turbotrace', 'turbotrace',
'transpilePackages', 'transpilePackages',
'skipMiddlewareUrlNormalize', 'skipProxyUrlNormalize',
'skipTrailingSlashRedirect', 'skipTrailingSlashRedirect',
'modularizeImports', 'modularizeImports',
'esmExternals', 'esmExternals',
......
...@@ -94,6 +94,7 @@ export function getCloneableBody<T extends IncomingMessage>( ...@@ -94,6 +94,7 @@ export function getCloneableBody<T extends IncomingMessage>(
limitExceeded = true limitExceeded = true
const urlInfo = readable.url ? ` for ${readable.url}` : '' const urlInfo = readable.url ? ` for ${readable.url}` : ''
console.warn( console.warn(
// TODO(jiwon): Update this document link
`Request body exceeded ${bytes.format(bodySizeLimit)}${urlInfo}. Only the first ${bytes.format(bodySizeLimit)} will be available unless configured. See https://nextjs.org/docs/app/api-reference/config/next-config-js/middlewareClientMaxBodySize for more details.` `Request body exceeded ${bytes.format(bodySizeLimit)}${urlInfo}. Only the first ${bytes.format(bodySizeLimit)} will be available unless configured. See https://nextjs.org/docs/app/api-reference/config/next-config-js/middlewareClientMaxBodySize for more details.`
) )
p1.push(null) p1.push(null)
......
...@@ -215,6 +215,7 @@ export const experimentalSchema = { ...@@ -215,6 +215,7 @@ export const experimentalSchema = {
extensionAlias: z.record(z.string(), z.any()).optional(), extensionAlias: z.record(z.string(), z.any()).optional(),
externalDir: z.boolean().optional(), externalDir: z.boolean().optional(),
externalMiddlewareRewritesResolve: z.boolean().optional(), externalMiddlewareRewritesResolve: z.boolean().optional(),
externalProxyRewritesResolve: z.boolean().optional(),
fallbackNodePolyfills: z.literal(false).optional(), fallbackNodePolyfills: z.literal(false).optional(),
fetchCacheKeyPrefix: z.string().optional(), fetchCacheKeyPrefix: z.string().optional(),
forceSwcTransforms: z.boolean().optional(), forceSwcTransforms: z.boolean().optional(),
...@@ -230,7 +231,9 @@ export const experimentalSchema = { ...@@ -230,7 +231,9 @@ export const experimentalSchema = {
linkNoTouchStart: z.boolean().optional(), linkNoTouchStart: z.boolean().optional(),
manualClientBasePath: z.boolean().optional(), manualClientBasePath: z.boolean().optional(),
middlewarePrefetch: z.enum(['strict', 'flexible']).optional(), middlewarePrefetch: z.enum(['strict', 'flexible']).optional(),
proxyPrefetch: z.enum(['strict', 'flexible']).optional(),
middlewareClientMaxBodySize: zSizeLimit.optional(), middlewareClientMaxBodySize: zSizeLimit.optional(),
proxyClientMaxBodySize: zSizeLimit.optional(),
multiZoneDraftMode: z.boolean().optional(), multiZoneDraftMode: z.boolean().optional(),
cssChunking: z.union([z.boolean(), z.literal('strict')]).optional(), cssChunking: z.union([z.boolean(), z.literal('strict')]).optional(),
nextScriptWorkers: z.boolean().optional(), nextScriptWorkers: z.boolean().optional(),
...@@ -673,6 +676,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -673,6 +676,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
serverExternalPackages: z.array(z.string()).optional(), serverExternalPackages: z.array(z.string()).optional(),
skipMiddlewareUrlNormalize: z.boolean().optional(), skipMiddlewareUrlNormalize: z.boolean().optional(),
skipProxyUrlNormalize: z.boolean().optional(),
skipTrailingSlashRedirect: z.boolean().optional(), skipTrailingSlashRedirect: z.boolean().optional(),
staticPageGenerationTimeout: z.number().optional(), staticPageGenerationTimeout: z.number().optional(),
expireTime: z.number().optional(), expireTime: z.number().optional(),
......
...@@ -326,7 +326,11 @@ export interface ExperimentalConfig { ...@@ -326,7 +326,11 @@ export interface ExperimentalConfig {
// e.g. 0.01 for 10% potential false matches lower // e.g. 0.01 for 10% potential false matches lower
// percent increases size of the filter // percent increases size of the filter
clientRouterFilterAllowedRate?: number clientRouterFilterAllowedRate?: number
/**
* @deprecated Use `externalProxyRewritesResolve` instead.
*/
externalMiddlewareRewritesResolve?: boolean externalMiddlewareRewritesResolve?: boolean
externalProxyRewritesResolve?: boolean
extensionAlias?: Record<string, any> extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[] allowedRevalidateHeaderKeys?: string[]
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
...@@ -340,7 +344,11 @@ export interface ExperimentalConfig { ...@@ -340,7 +344,11 @@ export interface ExperimentalConfig {
* @deprecated use config.expireTime instead * @deprecated use config.expireTime instead
*/ */
expireTime?: number expireTime?: number
/**
* @deprecated Use `proxyPrefetch` instead.
*/
middlewarePrefetch?: 'strict' | 'flexible' middlewarePrefetch?: 'strict' | 'flexible'
proxyPrefetch?: 'strict' | 'flexible'
manualClientBasePath?: boolean manualClientBasePath?: boolean
/** /**
* CSS Chunking strategy. Defaults to `true` ("loose" mode), which guesses dependencies * CSS Chunking strategy. Defaults to `true` ("loose" mode), which guesses dependencies
...@@ -793,9 +801,17 @@ export interface ExperimentalConfig { ...@@ -793,9 +801,17 @@ export interface ExperimentalConfig {
/** /**
* Body size limit for request bodies with middleware configured. * Body size limit for request bodies with middleware configured.
* Defaults to 10MB. Can be specified as a number (bytes) or string (e.g. '5mb'). * Defaults to 10MB. Can be specified as a number (bytes) or string (e.g. '5mb').
*
* @deprecated Use `proxyClientMaxBodySize` instead.
*/ */
middlewareClientMaxBodySize?: SizeLimit middlewareClientMaxBodySize?: SizeLimit
/**
* Body size limit for request bodies with proxy configured.
* Defaults to 10MB. Can be specified as a number (bytes) or string (e.g. '5mb').
*/
proxyClientMaxBodySize?: SizeLimit
/** /**
* Enable the Model Context Protocol (MCP) server for AI-assisted development. * Enable the Model Context Protocol (MCP) server for AI-assisted development.
* When enabled, Next.js will expose an MCP server at `/_next/mcp` that provides * When enabled, Next.js will expose an MCP server at `/_next/mcp` that provides
...@@ -1234,8 +1250,13 @@ export interface NextConfig { ...@@ -1234,8 +1250,13 @@ export interface NextConfig {
*/ */
turbopack?: TurbopackOptions turbopack?: TurbopackOptions
/**
* @deprecated Use `skipProxyUrlNormalize` instead.
*/
skipMiddlewareUrlNormalize?: boolean skipMiddlewareUrlNormalize?: boolean
skipProxyUrlNormalize?: boolean
skipTrailingSlashRedirect?: boolean skipTrailingSlashRedirect?: boolean
modularizeImports?: Record< modularizeImports?: Record<
...@@ -1441,7 +1462,7 @@ export const defaultConfig = Object.freeze({ ...@@ -1441,7 +1462,7 @@ export const defaultConfig = Object.freeze({
clientRouterFilter: true, clientRouterFilter: true,
clientRouterFilterRedirects: false, clientRouterFilterRedirects: false,
fetchCacheKeyPrefix: '', fetchCacheKeyPrefix: '',
middlewarePrefetch: 'flexible', proxyPrefetch: 'flexible',
optimisticClientCache: true, optimisticClientCache: true,
manualClientBasePath: false, manualClientBasePath: false,
cpus: Math.max( cpus: Math.max(
...@@ -1506,7 +1527,7 @@ export const defaultConfig = Object.freeze({ ...@@ -1506,7 +1527,7 @@ export const defaultConfig = Object.freeze({
browserDebugInfoInTerminal: false, browserDebugInfoInTerminal: false,
lockDistDir: true, lockDistDir: true,
isolatedDevBuild: true, isolatedDevBuild: true,
middlewareClientMaxBodySize: 10_485_760, // 10MB proxyClientMaxBodySize: 10_485_760, // 10MB
hideLogsAfterAbort: false, hideLogsAfterAbort: false,
}, },
htmlLimitedBots: undefined, htmlLimitedBots: undefined,
......
...@@ -139,6 +139,31 @@ function checkDeprecations( ...@@ -139,6 +139,31 @@ function checkDeprecations(
) )
} }
warnOptionHasBeenDeprecated(
userConfig,
'experimental.middlewarePrefetch',
`\`experimental.middlewarePrefetch\` is deprecated. Please use \`experimental.proxyPrefetch\` instead in ${configFileName}.`,
silent
)
warnOptionHasBeenDeprecated(
userConfig,
'experimental.middlewareClientMaxBodySize',
`\`experimental.middlewareClientMaxBodySize\` is deprecated. Please use \`experimental.proxyClientMaxBodySize\` instead in ${configFileName}.`,
silent
)
warnOptionHasBeenDeprecated(
userConfig,
'experimental.externalMiddlewareRewritesResolve',
`\`experimental.externalMiddlewareRewritesResolve\` is deprecated. Please use \`experimental.externalProxyRewritesResolve\` instead in ${configFileName}.`,
silent
)
warnOptionHasBeenDeprecated(
userConfig,
'skipMiddlewareUrlNormalize',
`\`skipMiddlewareUrlNormalize\` is deprecated. Please use \`skipProxyUrlNormalize\` instead in ${configFileName}.`,
silent
)
warnOptionHasBeenDeprecated( warnOptionHasBeenDeprecated(
userConfig, userConfig,
'experimental.instrumentationHook', 'experimental.instrumentationHook',
...@@ -728,18 +753,80 @@ function assignDefaultsAndValidate( ...@@ -728,18 +753,80 @@ function assignDefaultsAndValidate(
} }
} }
// Normalize & validate experimental.middlewareClientMaxBodySize // Throw if both Middleware and Proxy config are set.
if (typeof result.experimental?.middlewareClientMaxBodySize !== 'undefined') { if (
const middlewareClientMaxBodySize = userConfig.experimental?.proxyClientMaxBodySize !== undefined &&
result.experimental.middlewareClientMaxBodySize userConfig.experimental?.middlewareClientMaxBodySize !== undefined
) {
throw new Error(
'Config options `experimental.proxyClientMaxBodySize` and `experimental.middlewareClientMaxBodySize` cannot be set at the same time. Please use `experimental.proxyClientMaxBodySize` instead.'
)
}
if (
userConfig.experimental?.proxyPrefetch !== undefined &&
userConfig.experimental?.middlewarePrefetch !== undefined
) {
throw new Error(
'Config options `experimental.proxyPrefetch` and `experimental.middlewarePrefetch` cannot be set at the same time. Please use `experimental.proxyPrefetch` instead.'
)
}
if (
userConfig.experimental?.externalProxyRewritesResolve !== undefined &&
userConfig.experimental?.externalMiddlewareRewritesResolve !== undefined
) {
throw new Error(
'Config options `experimental.externalProxyRewritesResolve` and `experimental.externalMiddlewareRewritesResolve` cannot be set at the same time. Please use `experimental.externalProxyRewritesResolve` instead.'
)
}
if (
userConfig.skipProxyUrlNormalize !== undefined &&
userConfig.skipMiddlewareUrlNormalize !== undefined
) {
throw new Error(
'Config options `skipProxyUrlNormalize` and `skipMiddlewareUrlNormalize` cannot be set at the same time. Please use `skipProxyUrlNormalize` instead.'
)
}
// Map Proxy config to Middleware config as it is currently an alias.
if (
userConfig.experimental?.proxyClientMaxBodySize === undefined &&
userConfig.experimental?.middlewareClientMaxBodySize !== undefined
) {
result.experimental.proxyClientMaxBodySize =
userConfig.experimental.middlewareClientMaxBodySize
}
if (
userConfig.experimental?.proxyPrefetch === undefined &&
userConfig.experimental?.middlewarePrefetch !== undefined
) {
result.experimental.proxyPrefetch =
userConfig.experimental.middlewarePrefetch
}
if (
userConfig.experimental?.externalProxyRewritesResolve === undefined &&
userConfig.experimental?.externalMiddlewareRewritesResolve !== undefined
) {
result.experimental.externalProxyRewritesResolve =
userConfig.experimental.externalMiddlewareRewritesResolve
}
if (
userConfig.skipProxyUrlNormalize === undefined &&
userConfig.skipMiddlewareUrlNormalize !== undefined
) {
result.skipProxyUrlNormalize = userConfig.skipMiddlewareUrlNormalize
}
// Normalize & validate experimental.proxyClientMaxBodySize
if (typeof result.experimental?.proxyClientMaxBodySize !== 'undefined') {
const proxyClientMaxBodySize = result.experimental.proxyClientMaxBodySize
let normalizedValue: number let normalizedValue: number
if (typeof middlewareClientMaxBodySize === 'string') { if (typeof proxyClientMaxBodySize === 'string') {
const bytes = const bytes =
require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes') require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')
normalizedValue = bytes.parse(middlewareClientMaxBodySize) normalizedValue = bytes.parse(proxyClientMaxBodySize)
} else if (typeof middlewareClientMaxBodySize === 'number') { } else if (typeof proxyClientMaxBodySize === 'number') {
normalizedValue = middlewareClientMaxBodySize normalizedValue = proxyClientMaxBodySize
} else { } else {
throw new Error( throw new Error(
'Client Max Body Size must be a valid number (bytes) or filesize format string (e.g., "5mb")' 'Client Max Body Size must be a valid number (bytes) or filesize format string (e.g., "5mb")'
...@@ -751,7 +838,7 @@ function assignDefaultsAndValidate( ...@@ -751,7 +838,7 @@ function assignDefaultsAndValidate(
} }
// Store the normalized value as a number // Store the normalized value as a number
result.experimental.middlewareClientMaxBodySize = normalizedValue result.experimental.proxyClientMaxBodySize = normalizedValue
} }
warnOptionHasBeenMovedOutOfExperimental( warnOptionHasBeenMovedOutOfExperimental(
......
...@@ -171,7 +171,7 @@ export function getResolveRoutes( ...@@ -171,7 +171,7 @@ export function getResolveRoutes(
addRequestMeta(req, 'initProtocol', protocol) addRequestMeta(req, 'initProtocol', protocol)
if (!isUpgradeReq) { if (!isUpgradeReq) {
const bodySizeLimit = config.experimental.middlewareClientMaxBodySize as const bodySizeLimit = config.experimental.proxyClientMaxBodySize as
| number | number
| undefined | undefined
addRequestMeta(req, 'clonableBody', getCloneableBody(req, bodySizeLimit)) addRequestMeta(req, 'clonableBody', getCloneableBody(req, bodySizeLimit))
...@@ -180,7 +180,7 @@ export function getResolveRoutes( ...@@ -180,7 +180,7 @@ export function getResolveRoutes(
const maybeAddTrailingSlash = (pathname: string) => { const maybeAddTrailingSlash = (pathname: string) => {
if ( if (
config.trailingSlash && config.trailingSlash &&
!config.skipMiddlewareUrlNormalize && !config.skipProxyUrlNormalize &&
!pathname.endsWith('/') !pathname.endsWith('/')
) { ) {
return `${pathname}/` return `${pathname}/`
......
...@@ -113,7 +113,7 @@ export interface DevRoutesManifest { ...@@ -113,7 +113,7 @@ export interface DevRoutesManifest {
redirects: RoutesManifest['redirects'] redirects: RoutesManifest['redirects']
headers: RoutesManifest['headers'] headers: RoutesManifest['headers']
i18n: RoutesManifest['i18n'] i18n: RoutesManifest['i18n']
skipMiddlewareUrlNormalize: RoutesManifest['skipMiddlewareUrlNormalize'] skipProxyUrlNormalize: RoutesManifest['skipProxyUrlNormalize']
} }
export type ServerFields = { export type ServerFields = {
...@@ -254,7 +254,7 @@ async function startWatcher( ...@@ -254,7 +254,7 @@ async function startWatcher(
redirects: opts.fsChecker.redirects, redirects: opts.fsChecker.redirects,
headers: opts.fsChecker.headers, headers: opts.fsChecker.headers,
i18n: nextConfig.i18n || undefined, i18n: nextConfig.i18n || undefined,
skipMiddlewareUrlNormalize: nextConfig.skipMiddlewareUrlNormalize, skipProxyUrlNormalize: nextConfig.skipProxyUrlNormalize,
} }
await fs.promises.writeFile( await fs.promises.writeFile(
routesManifestPath, routesManifestPath,
......
...@@ -1652,7 +1652,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1652,7 +1652,7 @@ export default class NextNodeServer extends BaseServer<
let url: string let url: string
if (this.nextConfig.skipMiddlewareUrlNormalize) { if (this.nextConfig.skipProxyUrlNormalize) {
url = getRequestMeta(params.request, 'initURL')! url = getRequestMeta(params.request, 'initURL')!
} else { } else {
// For middleware to "fetch" we must always provide an absolute URL // For middleware to "fetch" we must always provide an absolute URL
...@@ -1957,7 +1957,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1957,7 +1957,7 @@ export default class NextNodeServer extends BaseServer<
if (!isUpgradeReq) { if (!isUpgradeReq) {
const bodySizeLimit = this.nextConfig.experimental const bodySizeLimit = this.nextConfig.experimental
?.middlewareClientMaxBodySize as number | undefined ?.proxyClientMaxBodySize as number | undefined
addRequestMeta( addRequestMeta(
req, req,
'clonableBody', 'clonableBody',
......
...@@ -219,7 +219,7 @@ export abstract class RouteModule< ...@@ -219,7 +219,7 @@ export abstract class RouteModule<
headers: [], headers: [],
i18n: i18n:
(process.env.__NEXT_I18N_CONFIG as any as I18NConfig) || undefined, (process.env.__NEXT_I18N_CONFIG as any as I18NConfig) || undefined,
skipMiddlewareUrlNormalize: Boolean( skipProxyUrlNormalize: Boolean(
process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE
), ),
}, },
......
...@@ -6,8 +6,13 @@ import type { CloneableBody } from '../body-streams' ...@@ -6,8 +6,13 @@ import type { CloneableBody } from '../body-streams'
import type { OutgoingHttpHeaders } from 'http' import type { OutgoingHttpHeaders } from 'http'
import type { FetchMetrics } from '../base-http' import type { FetchMetrics } from '../base-http'
/**
* @deprecated Use `ProxyConfig` instead. Middleware has been renamed to Proxy.
*/
export type { MiddlewareConfigInput as MiddlewareConfig } from '../../build/segment-config/middleware/middleware-config' export type { MiddlewareConfigInput as MiddlewareConfig } from '../../build/segment-config/middleware/middleware-config'
export type { MiddlewareConfigInput as ProxyConfig } from '../../build/segment-config/middleware/middleware-config'
export interface RequestData { export interface RequestData {
headers: OutgoingHttpHeaders headers: OutgoingHttpHeaders
method: string method: string
...@@ -54,9 +59,20 @@ export type NextMiddlewareResult = ...@@ -54,9 +59,20 @@ export type NextMiddlewareResult =
* by rewriting, redirecting, modifying the request or response headers, * by rewriting, redirecting, modifying the request or response headers,
* or responding directly. * or responding directly.
* *
* @deprecated Use `NextProxy` instead. Middleware has been renamed to Proxy.
* Read more: [Next.js Docs: Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware) * Read more: [Next.js Docs: Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware)
*/ */
export type NextMiddleware = ( export type NextMiddleware = (
request: NextRequest, request: NextRequest,
event: NextFetchEvent event: NextFetchEvent
) => NextMiddlewareResult | Promise<NextMiddlewareResult> ) => NextMiddlewareResult | Promise<NextMiddlewareResult>
/**
* Proxy allows you to run code before a request is completed.
* Then, based on the incoming request, you can modify the response
* by rewriting, redirecting, modifying the request or response headers,
* or responding directly.
*
* Read more: [Next.js Docs: Proxy](https://nextjs.org/docs/app/building-your-application/routing/middleware)
*/
export type NextProxy = NextMiddleware
...@@ -188,7 +188,7 @@ export type EventBuildFeatureUsage = { ...@@ -188,7 +188,7 @@ export type EventBuildFeatureUsage = {
| 'turbotrace' | 'turbotrace'
| 'vercelImageGeneration' | 'vercelImageGeneration'
| 'transpilePackages' | 'transpilePackages'
| 'skipMiddlewareUrlNormalize' | 'skipProxyUrlNormalize'
| 'skipTrailingSlashRedirect' | 'skipTrailingSlashRedirect'
| 'modularizeImports' | 'modularizeImports'
| 'esmExternals' | 'esmExternals'
......
...@@ -83,7 +83,7 @@ exports[`next.rs api should detect the correct routes: diagnostics 1`] = ` ...@@ -83,7 +83,7 @@ exports[`next.rs api should detect the correct routes: diagnostics 1`] = `
"category": "NextFeatureTelemetry_category_tbd", "category": "NextFeatureTelemetry_category_tbd",
"name": "EVENT_BUILD_FEATURE_USAGE", "name": "EVENT_BUILD_FEATURE_USAGE",
"payload": { "payload": {
"skipMiddlewareUrlNormalize": "false", "skipProxyUrlNormalize": "false",
}, },
}, },
{ {
......
...@@ -11,7 +11,7 @@ export async function middleware(req) { ...@@ -11,7 +11,7 @@ export async function middleware(req) {
} }
/** /**
* @type {import('next/server').MiddlewareConfig} * @type {import('next/server').ProxyConfig}
*/ */
export const config = { export const config = {
runtime: 'nodejs', runtime: 'nodejs',
......
import type { MiddlewareConfig } from 'next/server' import type { ProxyConfig } from 'next/server'
export default async function middleware() { export default async function middleware() {
// This import should not be instrumented. // This import should not be instrumented.
...@@ -7,6 +7,6 @@ export default async function middleware() { ...@@ -7,6 +7,6 @@ export default async function middleware() {
await import('./messages') await import('./messages')
} }
export const config: MiddlewareConfig = { export const config: ProxyConfig = {
matcher: ['/not-instrumented/middleware'], matcher: ['/not-instrumented/middleware'],
} }
...@@ -83,7 +83,7 @@ describe('client-max-body-size', () => { ...@@ -83,7 +83,7 @@ describe('client-max-body-size', () => {
skipDeployment: true, skipDeployment: true,
nextConfig: { nextConfig: {
experimental: { experimental: {
middlewareClientMaxBodySize: '5mb', proxyClientMaxBodySize: '5mb',
}, },
}, },
}) })
...@@ -142,7 +142,7 @@ describe('client-max-body-size', () => { ...@@ -142,7 +142,7 @@ describe('client-max-body-size', () => {
skipDeployment: true, skipDeployment: true,
nextConfig: { nextConfig: {
experimental: { experimental: {
middlewareClientMaxBodySize: 2 * 1024 * 1024, // 2MB in bytes proxyClientMaxBodySize: 2 * 1024 * 1024, // 2MB in bytes
}, },
}, },
}) })
...@@ -201,7 +201,7 @@ describe('client-max-body-size', () => { ...@@ -201,7 +201,7 @@ describe('client-max-body-size', () => {
skipDeployment: true, skipDeployment: true,
nextConfig: { nextConfig: {
experimental: { experimental: {
middlewareClientMaxBodySize: '50mb', proxyClientMaxBodySize: '50mb',
}, },
}, },
}) })
......
...@@ -32,6 +32,23 @@ describe('deprecation-warnings', () => { ...@@ -32,6 +32,23 @@ describe('deprecation-warnings', () => {
// Should warn about experimental.instrumentationHook // Should warn about experimental.instrumentationHook
expect(logs).toContain('experimental.instrumentationHook') expect(logs).toContain('experimental.instrumentationHook')
expect(logs).toContain('no longer needed') expect(logs).toContain('no longer needed')
// Should warn about middleware config options
expect(logs).toContain('experimental.middlewarePrefetch')
expect(logs).toContain('Please use `experimental.proxyPrefetch` instead')
expect(logs).toContain('experimental.middlewareClientMaxBodySize')
expect(logs).toContain(
'Please use `experimental.proxyClientMaxBodySize` instead'
)
expect(logs).toContain('experimental.externalMiddlewareRewritesResolve')
expect(logs).toContain(
'Please use `experimental.externalProxyRewritesResolve` instead'
)
expect(logs).toContain('skipMiddlewareUrlNormalize')
expect(logs).toContain('Please use `skipProxyUrlNormalize` instead')
}) })
}) })
}) })
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
// Explicitly configure deprecated options // Explicitly configure deprecated options
skipMiddlewareUrlNormalize: true,
experimental: { experimental: {
middlewarePrefetch: 'strict',
instrumentationHook: true, instrumentationHook: true,
middlewareClientMaxBodySize: '5mb',
externalMiddlewareRewritesResolve: true,
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
skipMiddlewareUrlNormalize: true, skipProxyUrlNormalize: true,
skipTrailingSlashRedirect: true, skipTrailingSlashRedirect: true,
experimental: { experimental: {
externalMiddlewareRewritesResolve: true, externalProxyRewritesResolve: true,
}, },
i18n: { i18n: {
locales: ['en', 'ja-jp'], locales: ['en', 'ja-jp'],
......
...@@ -228,7 +228,7 @@ describe('skip-trailing-slash-redirect', () => { ...@@ -228,7 +228,7 @@ describe('skip-trailing-slash-redirect', () => {
} }
}) })
it('should provide original _next/data URL with skipMiddlewareUrlNormalize', async () => { it('should provide original _next/data URL with skipProxyUrlNormalize', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
next.url, next.url,
`/_next/data/${next.buildId}/valid.json`, `/_next/data/${next.buildId}/valid.json`,
......
module.exports = { module.exports = {
skipMiddlewareUrlNormalize: true, skipProxyUrlNormalize: true,
skipTrailingSlashRedirect: true, skipTrailingSlashRedirect: true,
} }
\ No newline at end of file
...@@ -513,7 +513,7 @@ describe('config telemetry', () => { ...@@ -513,7 +513,7 @@ describe('config telemetry', () => {
) )
// eslint-disable-next-line jest/no-standalone-expect // eslint-disable-next-line jest/no-standalone-expect
expect(featureUsageEvents).toContainEqual({ expect(featureUsageEvents).toContainEqual({
featureName: 'skipMiddlewareUrlNormalize', featureName: 'skipProxyUrlNormalize',
invocationCount: 1, invocationCount: 1,
}) })
// eslint-disable-next-line jest/no-standalone-expect // eslint-disable-next-line jest/no-standalone-expect
......
import { import { NextProxy, NextResponse, URLPattern, ProxyConfig } from 'next/server'
NextMiddleware,
NextResponse,
URLPattern,
MiddlewareConfig,
} from 'next/server'
export const middleware: NextMiddleware = function (request) { export const middleware: NextProxy = function (request) {
const pattern = new URLPattern({ const pattern = new URLPattern({
pathname: '/:path', pathname: '/:path',
}) })
...@@ -27,4 +22,4 @@ export const middleware: NextMiddleware = function (request) { ...@@ -27,4 +22,4 @@ export const middleware: NextMiddleware = function (request) {
export const config = { export const config = {
matcher: ['/:path*'], matcher: ['/:path*'],
regions: [], regions: [],
} satisfies MiddlewareConfig } satisfies ProxyConfig
module.exports = {
i18n: {
locales: ['en', 'fr', 'nl'],
defaultLocale: 'en',
},
}
export default function Index() {
return <p className="title">Static route</p>
}
import { NextProxy, NextResponse, URLPattern, ProxyConfig } from 'next/server'
export const proxy: NextProxy = function (request) {
const pattern = new URLPattern({
pathname: '/:path',
})
console.log(pattern.test(request.nextUrl.pathname))
if (request.nextUrl.pathname === '/static') {
return new NextResponse(null, {
headers: {
data: 'hello from proxy',
'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname,
'req-url-query': request.nextUrl.searchParams.get('foo') || '',
'req-url-locale': request.nextUrl.locale,
},
})
}
}
export const config = {
matcher: ['/:path*'],
regions: [],
} satisfies ProxyConfig
/* eslint-env jest */
import { join } from 'path'
import { nextTestSetup } from 'e2e-utils'
describe('proxy-typescript', () => {
const { next } = nextTestSetup({
files: join(__dirname, '../app'),
})
it('should have built and started', async () => {
const response = await next.fetch('/static')
expect(response.headers.get('data')).toEqual('hello from proxy')
})
})
...@@ -9941,7 +9941,7 @@ ...@@ -9941,7 +9941,7 @@
"skip-trailing-slash-redirect should not apply trailing slash on load on client", "skip-trailing-slash-redirect should not apply trailing slash on load on client",
"skip-trailing-slash-redirect should not have trailing slash redirects in manifest", "skip-trailing-slash-redirect should not have trailing slash redirects in manifest",
"skip-trailing-slash-redirect should parse locale info for data request correctly", "skip-trailing-slash-redirect should parse locale info for data request correctly",
"skip-trailing-slash-redirect should provide original _next/data URL with skipMiddlewareUrlNormalize" "skip-trailing-slash-redirect should provide original _next/data URL with skipProxyUrlNormalize"
], ],
"failed": [], "failed": [],
"pending": [], "pending": [],
...@@ -11853,7 +11853,7 @@ ...@@ -11853,7 +11853,7 @@
"skip-trailing-slash-redirect should merge cookies from middleware and edge API routes correctly", "skip-trailing-slash-redirect should merge cookies from middleware and edge API routes correctly",
"skip-trailing-slash-redirect should not apply trailing slash on load on client", "skip-trailing-slash-redirect should not apply trailing slash on load on client",
"skip-trailing-slash-redirect should parse locale info for data request correctly", "skip-trailing-slash-redirect should parse locale info for data request correctly",
"skip-trailing-slash-redirect should provide original _next/data URL with skipMiddlewareUrlNormalize" "skip-trailing-slash-redirect should provide original _next/data URL with skipProxyUrlNormalize"
], ],
"failed": [], "failed": [],
"pending": [], "pending": [],
...@@ -8545,7 +8545,7 @@ ...@@ -8545,7 +8545,7 @@
"skip-trailing-slash-redirect should not apply trailing slash on load on client", "skip-trailing-slash-redirect should not apply trailing slash on load on client",
"skip-trailing-slash-redirect should not have trailing slash redirects in manifest", "skip-trailing-slash-redirect should not have trailing slash redirects in manifest",
"skip-trailing-slash-redirect should parse locale info for data request correctly", "skip-trailing-slash-redirect should parse locale info for data request correctly",
"skip-trailing-slash-redirect should provide original _next/data URL with skipMiddlewareUrlNormalize" "skip-trailing-slash-redirect should provide original _next/data URL with skipProxyUrlNormalize"
], ],
"failed": [], "failed": [],
"pending": [], "pending": [],
...@@ -12075,7 +12075,7 @@ ...@@ -12075,7 +12075,7 @@
"skip-trailing-slash-redirect should merge cookies from middleware and edge API routes correctly", "skip-trailing-slash-redirect should merge cookies from middleware and edge API routes correctly",
"skip-trailing-slash-redirect should not apply trailing slash on load on client", "skip-trailing-slash-redirect should not apply trailing slash on load on client",
"skip-trailing-slash-redirect should parse locale info for data request correctly", "skip-trailing-slash-redirect should parse locale info for data request correctly",
"skip-trailing-slash-redirect should provide original _next/data URL with skipMiddlewareUrlNormalize" "skip-trailing-slash-redirect should provide original _next/data URL with skipProxyUrlNormalize"
], ],
"failed": [], "failed": [],
"pending": [], "pending": [],
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