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 {
let config = self.next_config();
emit_event(
"skipMiddlewareUrlNormalize",
*config.skip_middleware_url_normalize().await?,
"skipProxyUrlNormalize",
*config.skip_proxy_url_normalize().await?,
);
emit_event(
......
......@@ -69,7 +69,7 @@
"clientRouterFilter": true,
"clientRouterFilterRedirects": false,
"fetchCacheKeyPrefix": "",
"middlewarePrefetch": "flexible",
"proxyPrefetch": "flexible",
"optimisticClientCache": true,
"manualClientBasePath": false,
"cpus": 2,
......
......@@ -102,7 +102,7 @@ pub struct NextConfig {
trailing_slash: Option<bool>,
asset_prefix: Option<RcStr>,
base_path: Option<RcStr>,
skip_middleware_url_normalize: Option<bool>,
skip_proxy_url_normalize: Option<bool>,
skip_trailing_slash_redirect: Option<bool>,
i18n: Option<I18NConfig>,
cross_origin: Option<CrossOriginConfig>,
......@@ -1660,8 +1660,8 @@ impl NextConfig {
}
#[turbo_tasks::function]
pub fn skip_middleware_url_normalize(&self) -> Vc<bool> {
Vc::cell(self.skip_middleware_url_normalize.unwrap_or(false))
pub fn skip_proxy_url_normalize(&self) -> Vc<bool> {
Vc::cell(self.skip_proxy_url_normalize.unwrap_or(false))
}
#[turbo_tasks::function]
......
......@@ -572,7 +572,7 @@ async fn parse_config_value(
) -> Result<()> {
let get_value = || {
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.
let init = if let Some(Expr::TsSatisfies(TsSatisfiesExpr { expr, .. })) = init {
Some(&**expr)
......
......@@ -874,5 +874,9 @@
"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.",
"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 {
export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event'
export { NextRequest } from 'next/dist/server/web/spec-extension/request'
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 { userAgent } from 'next/dist/server/web/spec-extension/user-agent'
export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url'
......
......@@ -47,7 +47,7 @@ export type MiddlewareMatcher = {
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),
* [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 {
generateStaticParams?: boolean
generateSitemaps?: boolean
generateImageMetadata?: boolean
middleware?: MiddlewareConfig
middleware?: ProxyConfig
config: Omit<AppSegmentConfig, 'runtime' | 'maxDuration'> | undefined
runtime: AppSegmentConfig['runtime'] | undefined
preferredRegion: AppSegmentConfig['preferredRegion'] | undefined
......@@ -90,7 +90,7 @@ export interface PagesPageStaticInfo {
generateStaticParams?: boolean
generateSitemaps?: boolean
generateImageMetadata?: boolean
middleware?: MiddlewareConfig
middleware?: ProxyConfig
config:
| (Omit<PagesSegmentConfig, 'runtime' | 'config' | 'maxDuration'> & {
config?: Omit<PagesSegmentConfigConfig, 'runtime' | 'maxDuration'>
......@@ -372,7 +372,7 @@ function parseMiddlewareConfig(
page: string,
rawConfig: unknown,
nextConfig: NextConfig
): MiddlewareConfig {
): ProxyConfig {
// If there's no config to parse, then return nothing.
if (typeof rawConfig !== 'object' || !rawConfig) return {}
......@@ -386,7 +386,7 @@ function parseMiddlewareConfig(
process.exit(1)
}
const config: MiddlewareConfig = {}
const config: ProxyConfig = {}
if (input.data.matcher) {
config.matchers = getMiddlewareMatchers(input.data.matcher, nextConfig)
......
......@@ -214,7 +214,7 @@ export function getDefineEnv({
'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':
config.experimental.optimisticClientCache ?? true,
'process.env.__NEXT_MIDDLEWARE_PREFETCH':
config.experimental.middlewarePrefetch ?? 'flexible',
config.experimental.proxyPrefetch ?? 'flexible',
'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,
'process.browser': isClient,
'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false,
......@@ -263,9 +263,9 @@ export function getDefineEnv({
'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false,
'process.env.__NEXT_I18N_CONFIG': config.i18n || '',
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':
config.skipMiddlewareUrlNormalize,
config.skipProxyUrlNormalize,
'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':
config.experimental.externalMiddlewareRewritesResolve ?? false,
config.experimental.externalProxyRewritesResolve ?? false,
'process.env.__NEXT_MANUAL_TRAILING_SLASH':
config.skipTrailingSlashRedirect,
'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION':
......
......@@ -5,7 +5,7 @@ import type { EdgeAppRouteLoaderQuery } from './webpack/loaders/next-edge-app-ro
import type { NextConfigComplete } from '../server/config-shared'
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type {
MiddlewareConfig,
ProxyConfig,
MiddlewareMatcher,
PageStaticInfo,
} from './analysis/get-page-static-info'
......@@ -595,12 +595,12 @@ export function getEdgeServerEntry(opts: {
isServerComponent: boolean
page: string
pages: MappedPages
middleware?: Partial<MiddlewareConfig>
middleware?: Partial<ProxyConfig>
pagesType: PAGE_TYPES
appDirLoader?: string
hasInstrumentationHook?: boolean
preferredRegion: string | string[] | undefined
middlewareConfig?: MiddlewareConfig
middlewareConfig?: ProxyConfig
}) {
if (
opts.pagesType === 'app' &&
......
......@@ -485,7 +485,7 @@ export type RoutesManifest = {
pathHeader: typeof NEXT_REWRITTEN_PATH_HEADER
queryHeader: typeof NEXT_REWRITTEN_QUERY_HEADER
}
skipMiddlewareUrlNormalize?: boolean
skipProxyUrlNormalize?: boolean
caseSensitive?: boolean
/**
* Configuration related to Partial Prerendering.
......@@ -1605,7 +1605,7 @@ export default async function build(
pathHeader: NEXT_REWRITTEN_PATH_HEADER,
queryHeader: NEXT_REWRITTEN_QUERY_HEADER,
},
skipMiddlewareUrlNormalize: config.skipMiddlewareUrlNormalize,
skipProxyUrlNormalize: config.skipProxyUrlNormalize,
ppr: isAppPPREnabled
? {
chain: {
......
......@@ -952,7 +952,7 @@ export default async function getBaseWebpackConfig(
['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource],
['swcEmotion', !!config.compiler?.emotion],
['transpilePackages', !!config.transpilePackages],
['skipMiddlewareUrlNormalize', !!config.skipMiddlewareUrlNormalize],
['skipProxyUrlNormalize', !!config.skipProxyUrlNormalize],
['skipTrailingSlashRedirect', !!config.skipTrailingSlashRedirect],
['modularizeImports', !!config.modularizeImports],
// If esmExternals is not same as default value, it represents customized usage
......
import type {
MiddlewareConfig,
ProxyConfig,
MiddlewareMatcher,
RSCModuleType,
} from '../../analysis/get-page-static-info'
......@@ -39,7 +39,7 @@ export interface RouteMeta {
page: string
absolutePagePath: string
preferredRegion: string | string[] | undefined
middlewareConfig: MiddlewareConfig
middlewareConfig: ProxyConfig
// references to other modules that this route needs
// e.g. related routes, not-found routes, etc
relatedModules?: string[]
......
......@@ -24,7 +24,7 @@ import { promises as fs } from 'fs'
import { isAppRouteRoute } from '../../../../lib/is-app-route-route'
import type { NextConfig } from '../../../../server/config-shared'
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 { loadEntrypoint } from '../../../load-entrypoint'
import {
......@@ -644,7 +644,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const buildInfo = getModuleBuildInfo((this as any)._module)
const collectedDeclarations: [string, string][] = []
const page = name.replace(/^app/, '')
const middlewareConfig: MiddlewareConfig = JSON.parse(
const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
buildInfo.route = {
......
......@@ -2,7 +2,7 @@ import { getModuleBuildInfo } from '../get-module-build-info'
import { stringifyRequest } from '../../stringify-request'
import type { webpack } from 'next/dist/compiled/webpack/webpack'
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 { isMetadataRoute } from '../../../../lib/metadata/is-metadata-route'
......@@ -29,7 +29,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
} = this.getOptions()
const appDirLoader = Buffer.from(appDirLoaderBase64, 'base64').toString()
const middlewareConfig: MiddlewareConfig = JSON.parse(
const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
......
import type webpack from 'webpack'
import { getModuleBuildInfo } from './get-module-build-info'
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 = {
absolutePagePath: string
......@@ -22,7 +22,7 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade
}: EdgeFunctionLoaderOptions = this.getOptions()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module as any)
const middlewareConfig: MiddlewareConfig = JSON.parse(
const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
buildInfo.route = {
......
import type webpack from 'webpack'
import type { SizeLimit } from '../../../../types'
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 { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
......@@ -90,7 +90,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
)
}
const middlewareConfig: MiddlewareConfig = JSON.parse(
const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
......
import type {
MiddlewareConfig,
ProxyConfig,
MiddlewareMatcher,
} from '../../analysis/get-page-static-info'
import { getModuleBuildInfo } from './get-module-build-info'
......@@ -45,7 +45,7 @@ export default async function middlewareLoader(this: any) {
absolutePagePath
)
const middlewareConfig: MiddlewareConfig = JSON.parse(
const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
const buildInfo = getModuleBuildInfo(this._module)
......
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 {
......@@ -18,7 +18,7 @@ type RouteLoaderOptionsPagesAPIInput = {
page: string
preferredRegion: string | string[] | undefined
absolutePagePath: string
middlewareConfig: MiddlewareConfig
middlewareConfig: ProxyConfig
}
type RouteLoaderOptionsPagesInput = {
......@@ -27,7 +27,7 @@ type RouteLoaderOptionsPagesInput = {
pages: MappedPages
preferredRegion: string | string[] | undefined
absolutePagePath: string
middlewareConfig: MiddlewareConfig
middlewareConfig: ProxyConfig
}
type RouteLoaderOptionsInput =
......@@ -148,9 +148,7 @@ const loadPages = async (
}: RouteLoaderPagesOptions,
buildInfo: ModuleBuildInfo
) => {
const middlewareConfig: MiddlewareConfig = decodeFromBase64(
middlewareConfigBase64
)
const middlewareConfig: ProxyConfig = decodeFromBase64(middlewareConfigBase64)
// Attach build info to the module.
buildInfo.route = {
......@@ -187,9 +185,7 @@ const loadPagesAPI = async (
}: RouteLoaderPagesAPIOptions,
buildInfo: ModuleBuildInfo
) => {
const middlewareConfig: MiddlewareConfig = decodeFromBase64(
middlewareConfigBase64
)
const middlewareConfig: ProxyConfig = decodeFromBase64(middlewareConfigBase64)
// Attach build info to the module.
buildInfo.route = {
......
......@@ -23,7 +23,7 @@ import {
INTERCEPTION_ROUTE_REWRITE_MANIFEST,
DYNAMIC_CSS_MANIFEST,
} 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 { traceGlobals } from '../../../trace/shared'
import { EVENT_BUILD_FEATURE_USAGE } from '../../../telemetry/events'
......@@ -294,7 +294,7 @@ function isBunModule(moduleName: string) {
function isDynamicCodeEvaluationAllowed(
fileName: string,
middlewareConfig?: MiddlewareConfig,
middlewareConfig?: ProxyConfig,
rootDir?: string
) {
// Some packages are known to use `eval` but are safe to use in the Edge
......
......@@ -415,7 +415,7 @@ function createServerDefinitions() {
export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event'
export { NextRequest } from 'next/dist/server/web/spec-extension/request'
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 { userAgent } from 'next/dist/server/web/spec-extension/user-agent'
export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url'
......
......@@ -43,7 +43,7 @@ export type Feature =
| `swc/target/${SWC_TARGET_TRIPLE}`
| 'turbotrace'
| 'transpilePackages'
| 'skipMiddlewareUrlNormalize'
| 'skipProxyUrlNormalize'
| 'skipTrailingSlashRedirect'
| 'modularizeImports'
| 'esmExternals'
......@@ -101,7 +101,7 @@ const BUILD_FEATURES: Array<Feature> = [
'swc/target/aarch64-pc-windows-msvc',
'turbotrace',
'transpilePackages',
'skipMiddlewareUrlNormalize',
'skipProxyUrlNormalize',
'skipTrailingSlashRedirect',
'modularizeImports',
'esmExternals',
......
......@@ -94,6 +94,7 @@ export function getCloneableBody<T extends IncomingMessage>(
limitExceeded = true
const urlInfo = readable.url ? ` for ${readable.url}` : ''
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.`
)
p1.push(null)
......
......@@ -215,6 +215,7 @@ export const experimentalSchema = {
extensionAlias: z.record(z.string(), z.any()).optional(),
externalDir: z.boolean().optional(),
externalMiddlewareRewritesResolve: z.boolean().optional(),
externalProxyRewritesResolve: z.boolean().optional(),
fallbackNodePolyfills: z.literal(false).optional(),
fetchCacheKeyPrefix: z.string().optional(),
forceSwcTransforms: z.boolean().optional(),
......@@ -230,7 +231,9 @@ export const experimentalSchema = {
linkNoTouchStart: z.boolean().optional(),
manualClientBasePath: z.boolean().optional(),
middlewarePrefetch: z.enum(['strict', 'flexible']).optional(),
proxyPrefetch: z.enum(['strict', 'flexible']).optional(),
middlewareClientMaxBodySize: zSizeLimit.optional(),
proxyClientMaxBodySize: zSizeLimit.optional(),
multiZoneDraftMode: z.boolean().optional(),
cssChunking: z.union([z.boolean(), z.literal('strict')]).optional(),
nextScriptWorkers: z.boolean().optional(),
......@@ -673,6 +676,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(),
serverExternalPackages: z.array(z.string()).optional(),
skipMiddlewareUrlNormalize: z.boolean().optional(),
skipProxyUrlNormalize: z.boolean().optional(),
skipTrailingSlashRedirect: z.boolean().optional(),
staticPageGenerationTimeout: z.number().optional(),
expireTime: z.number().optional(),
......
......@@ -326,7 +326,11 @@ export interface ExperimentalConfig {
// e.g. 0.01 for 10% potential false matches lower
// percent increases size of the filter
clientRouterFilterAllowedRate?: number
/**
* @deprecated Use `externalProxyRewritesResolve` instead.
*/
externalMiddlewareRewritesResolve?: boolean
externalProxyRewritesResolve?: boolean
extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[]
fetchCacheKeyPrefix?: string
......@@ -340,7 +344,11 @@ export interface ExperimentalConfig {
* @deprecated use config.expireTime instead
*/
expireTime?: number
/**
* @deprecated Use `proxyPrefetch` instead.
*/
middlewarePrefetch?: 'strict' | 'flexible'
proxyPrefetch?: 'strict' | 'flexible'
manualClientBasePath?: boolean
/**
* CSS Chunking strategy. Defaults to `true` ("loose" mode), which guesses dependencies
......@@ -793,9 +801,17 @@ export interface ExperimentalConfig {
/**
* Body size limit for request bodies with middleware configured.
* Defaults to 10MB. Can be specified as a number (bytes) or string (e.g. '5mb').
*
* @deprecated Use `proxyClientMaxBodySize` instead.
*/
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.
* When enabled, Next.js will expose an MCP server at `/_next/mcp` that provides
......@@ -1234,8 +1250,13 @@ export interface NextConfig {
*/
turbopack?: TurbopackOptions
/**
* @deprecated Use `skipProxyUrlNormalize` instead.
*/
skipMiddlewareUrlNormalize?: boolean
skipProxyUrlNormalize?: boolean
skipTrailingSlashRedirect?: boolean
modularizeImports?: Record<
......@@ -1441,7 +1462,7 @@ export const defaultConfig = Object.freeze({
clientRouterFilter: true,
clientRouterFilterRedirects: false,
fetchCacheKeyPrefix: '',
middlewarePrefetch: 'flexible',
proxyPrefetch: 'flexible',
optimisticClientCache: true,
manualClientBasePath: false,
cpus: Math.max(
......@@ -1506,7 +1527,7 @@ export const defaultConfig = Object.freeze({
browserDebugInfoInTerminal: false,
lockDistDir: true,
isolatedDevBuild: true,
middlewareClientMaxBodySize: 10_485_760, // 10MB
proxyClientMaxBodySize: 10_485_760, // 10MB
hideLogsAfterAbort: false,
},
htmlLimitedBots: undefined,
......
......@@ -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(
userConfig,
'experimental.instrumentationHook',
......@@ -728,18 +753,80 @@ function assignDefaultsAndValidate(
}
}
// Normalize & validate experimental.middlewareClientMaxBodySize
if (typeof result.experimental?.middlewareClientMaxBodySize !== 'undefined') {
const middlewareClientMaxBodySize =
result.experimental.middlewareClientMaxBodySize
// Throw if both Middleware and Proxy config are set.
if (
userConfig.experimental?.proxyClientMaxBodySize !== undefined &&
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
if (typeof middlewareClientMaxBodySize === 'string') {
if (typeof proxyClientMaxBodySize === 'string') {
const bytes =
require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')
normalizedValue = bytes.parse(middlewareClientMaxBodySize)
} else if (typeof middlewareClientMaxBodySize === 'number') {
normalizedValue = middlewareClientMaxBodySize
normalizedValue = bytes.parse(proxyClientMaxBodySize)
} else if (typeof proxyClientMaxBodySize === 'number') {
normalizedValue = proxyClientMaxBodySize
} else {
throw new Error(
'Client Max Body Size must be a valid number (bytes) or filesize format string (e.g., "5mb")'
......@@ -751,7 +838,7 @@ function assignDefaultsAndValidate(
}
// Store the normalized value as a number
result.experimental.middlewareClientMaxBodySize = normalizedValue
result.experimental.proxyClientMaxBodySize = normalizedValue
}
warnOptionHasBeenMovedOutOfExperimental(
......
......@@ -171,7 +171,7 @@ export function getResolveRoutes(
addRequestMeta(req, 'initProtocol', protocol)
if (!isUpgradeReq) {
const bodySizeLimit = config.experimental.middlewareClientMaxBodySize as
const bodySizeLimit = config.experimental.proxyClientMaxBodySize as
| number
| undefined
addRequestMeta(req, 'clonableBody', getCloneableBody(req, bodySizeLimit))
......@@ -180,7 +180,7 @@ export function getResolveRoutes(
const maybeAddTrailingSlash = (pathname: string) => {
if (
config.trailingSlash &&
!config.skipMiddlewareUrlNormalize &&
!config.skipProxyUrlNormalize &&
!pathname.endsWith('/')
) {
return `${pathname}/`
......
......@@ -113,7 +113,7 @@ export interface DevRoutesManifest {
redirects: RoutesManifest['redirects']
headers: RoutesManifest['headers']
i18n: RoutesManifest['i18n']
skipMiddlewareUrlNormalize: RoutesManifest['skipMiddlewareUrlNormalize']
skipProxyUrlNormalize: RoutesManifest['skipProxyUrlNormalize']
}
export type ServerFields = {
......@@ -254,7 +254,7 @@ async function startWatcher(
redirects: opts.fsChecker.redirects,
headers: opts.fsChecker.headers,
i18n: nextConfig.i18n || undefined,
skipMiddlewareUrlNormalize: nextConfig.skipMiddlewareUrlNormalize,
skipProxyUrlNormalize: nextConfig.skipProxyUrlNormalize,
}
await fs.promises.writeFile(
routesManifestPath,
......
......@@ -1652,7 +1652,7 @@ export default class NextNodeServer extends BaseServer<
let url: string
if (this.nextConfig.skipMiddlewareUrlNormalize) {
if (this.nextConfig.skipProxyUrlNormalize) {
url = getRequestMeta(params.request, 'initURL')!
} else {
// For middleware to "fetch" we must always provide an absolute URL
......@@ -1957,7 +1957,7 @@ export default class NextNodeServer extends BaseServer<
if (!isUpgradeReq) {
const bodySizeLimit = this.nextConfig.experimental
?.middlewareClientMaxBodySize as number | undefined
?.proxyClientMaxBodySize as number | undefined
addRequestMeta(
req,
'clonableBody',
......
......@@ -219,7 +219,7 @@ export abstract class RouteModule<
headers: [],
i18n:
(process.env.__NEXT_I18N_CONFIG as any as I18NConfig) || undefined,
skipMiddlewareUrlNormalize: Boolean(
skipProxyUrlNormalize: Boolean(
process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE
),
},
......
......@@ -6,8 +6,13 @@ import type { CloneableBody } from '../body-streams'
import type { OutgoingHttpHeaders } from '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 ProxyConfig } from '../../build/segment-config/middleware/middleware-config'
export interface RequestData {
headers: OutgoingHttpHeaders
method: string
......@@ -54,9 +59,20 @@ export type NextMiddlewareResult =
* by rewriting, redirecting, modifying the request or response headers,
* 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)
*/
export type NextMiddleware = (
request: NextRequest,
event: NextFetchEvent
) => 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 = {
| 'turbotrace'
| 'vercelImageGeneration'
| 'transpilePackages'
| 'skipMiddlewareUrlNormalize'
| 'skipProxyUrlNormalize'
| 'skipTrailingSlashRedirect'
| 'modularizeImports'
| 'esmExternals'
......
......@@ -83,7 +83,7 @@ exports[`next.rs api should detect the correct routes: diagnostics 1`] = `
"category": "NextFeatureTelemetry_category_tbd",
"name": "EVENT_BUILD_FEATURE_USAGE",
"payload": {
"skipMiddlewareUrlNormalize": "false",
"skipProxyUrlNormalize": "false",
},
},
{
......
......@@ -11,7 +11,7 @@ export async function middleware(req) {
}
/**
* @type {import('next/server').MiddlewareConfig}
* @type {import('next/server').ProxyConfig}
*/
export const config = {
runtime: 'nodejs',
......
import type { MiddlewareConfig } from 'next/server'
import type { ProxyConfig } from 'next/server'
export default async function middleware() {
// This import should not be instrumented.
......@@ -7,6 +7,6 @@ export default async function middleware() {
await import('./messages')
}
export const config: MiddlewareConfig = {
export const config: ProxyConfig = {
matcher: ['/not-instrumented/middleware'],
}
......@@ -83,7 +83,7 @@ describe('client-max-body-size', () => {
skipDeployment: true,
nextConfig: {
experimental: {
middlewareClientMaxBodySize: '5mb',
proxyClientMaxBodySize: '5mb',
},
},
})
......@@ -142,7 +142,7 @@ describe('client-max-body-size', () => {
skipDeployment: true,
nextConfig: {
experimental: {
middlewareClientMaxBodySize: 2 * 1024 * 1024, // 2MB in bytes
proxyClientMaxBodySize: 2 * 1024 * 1024, // 2MB in bytes
},
},
})
......@@ -201,7 +201,7 @@ describe('client-max-body-size', () => {
skipDeployment: true,
nextConfig: {
experimental: {
middlewareClientMaxBodySize: '50mb',
proxyClientMaxBodySize: '50mb',
},
},
})
......
......@@ -32,6 +32,23 @@ describe('deprecation-warnings', () => {
// Should warn about experimental.instrumentationHook
expect(logs).toContain('experimental.instrumentationHook')
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} */
module.exports = {
// Explicitly configure deprecated options
skipMiddlewareUrlNormalize: true,
experimental: {
middlewarePrefetch: 'strict',
instrumentationHook: true,
middlewareClientMaxBodySize: '5mb',
externalMiddlewareRewritesResolve: true,
},
}
/** @type {import('next').NextConfig} */
const nextConfig = {
skipMiddlewareUrlNormalize: true,
skipProxyUrlNormalize: true,
skipTrailingSlashRedirect: true,
experimental: {
externalMiddlewareRewritesResolve: true,
externalProxyRewritesResolve: true,
},
i18n: {
locales: ['en', 'ja-jp'],
......
......@@ -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(
next.url,
`/_next/data/${next.buildId}/valid.json`,
......
module.exports = {
skipMiddlewareUrlNormalize: true,
skipProxyUrlNormalize: true,
skipTrailingSlashRedirect: true,
}
\ No newline at end of file
......@@ -513,7 +513,7 @@ describe('config telemetry', () => {
)
// eslint-disable-next-line jest/no-standalone-expect
expect(featureUsageEvents).toContainEqual({
featureName: 'skipMiddlewareUrlNormalize',
featureName: 'skipProxyUrlNormalize',
invocationCount: 1,
})
// eslint-disable-next-line jest/no-standalone-expect
......
import {
NextMiddleware,
NextResponse,
URLPattern,
MiddlewareConfig,
} from 'next/server'
import { NextProxy, NextResponse, URLPattern, ProxyConfig } from 'next/server'
export const middleware: NextMiddleware = function (request) {
export const middleware: NextProxy = function (request) {
const pattern = new URLPattern({
pathname: '/:path',
})
......@@ -27,4 +22,4 @@ export const middleware: NextMiddleware = function (request) {
export const config = {
matcher: ['/:path*'],
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 @@
"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 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": [],
"pending": [],
......@@ -11853,7 +11853,7 @@
"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 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": [],
"pending": [],
......@@ -8545,7 +8545,7 @@
"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 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": [],
"pending": [],
......@@ -12075,7 +12075,7 @@
"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 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": [],
"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