Unverified Commit 1111200b authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Revert "[Breaking] Skip Next.js internal routes `/_next` in middleware" (#84697)

Reverts vercel/next.js#84239

[slack
thread](https://vercel.slack.com/archives/C06DGJ420TZ/p1760022841341369?thread_ts=1759907388.654779&cid=C06DGJ420TZ)
parent 396fed36
......@@ -42,31 +42,6 @@ use crate::{
route::{Endpoint, EndpointOutput, EndpointOutputPaths},
};
/// Rust implementation of the TypeScript getDefaultMiddlewareMatcher function
/// Generates default middleware matcher patterns that respect skipMiddlewareNextInternalRoutes
fn get_default_middleware_matcher(
skip_middleware_next_internal_routes: Option<bool>,
) -> MiddlewareMatcher {
let skip_internal = skip_middleware_next_internal_routes.unwrap_or(true);
if skip_internal {
// Skip "/_next/" internal routes, except for "/_next/data/" which is needed for
// client-side navigation. Do not consider basePath as the user cannot create a
// route starts with underscore.
MiddlewareMatcher {
regexp: Some(rcstr!("^(?!.*\\/\\_next\\/(?!data\\/)).*")),
original_source: rcstr!("/((?!_next/(?!data/))[^]*)*"),
..Default::default()
}
} else {
MiddlewareMatcher {
regexp: Some(rcstr!("^/.*$")),
original_source: rcstr!("/:path*"),
..Default::default()
}
}
}
#[turbo_tasks::value]
pub struct MiddlewareEndpoint {
project: ResolvedVc<Project>,
......@@ -190,8 +165,6 @@ impl MiddlewareEndpoint {
.map(|i18n| i18n.locales.len() > 1)
.unwrap_or(false);
let base_path = next_config.base_path().await?;
let skip_middleware_next_internal_routes =
next_config.skip_middleware_next_internal_routes().await?;
let matchers = if let Some(matchers) = config.middleware_matcher.as_ref() {
matchers
......@@ -243,9 +216,11 @@ impl MiddlewareEndpoint {
})
.collect()
} else {
vec![get_default_middleware_matcher(
*skip_middleware_next_internal_routes,
)]
vec![MiddlewareMatcher {
regexp: Some(rcstr!("^/.*$")),
original_source: rcstr!("/:path*"),
..Default::default()
}]
};
if matches!(runtime, NextRuntime::NodeJs) {
......
......@@ -103,7 +103,6 @@ pub struct NextConfig {
asset_prefix: Option<RcStr>,
base_path: Option<RcStr>,
skip_middleware_url_normalize: Option<bool>,
skip_middleware_next_internal_routes: Option<bool>,
skip_trailing_slash_redirect: Option<bool>,
i18n: Option<I18NConfig>,
cross_origin: Option<CrossOriginConfig>,
......@@ -1344,11 +1343,6 @@ impl NextConfig {
Vc::cell(self.base_path.clone())
}
#[turbo_tasks::function]
pub fn skip_middleware_next_internal_routes(&self) -> Vc<Option<bool>> {
Vc::cell(self.skip_middleware_next_internal_routes)
}
#[turbo_tasks::function]
pub fn cache_handler(&self, project_path: FileSystemPath) -> Result<Vc<OptionFileSystemPath>> {
if let Some(handler) = &self.cache_handler {
......
......@@ -47,7 +47,6 @@ import {
isInstrumentationHookFilename,
} from './utils'
import { getPageStaticInfo } from './analysis/get-page-static-info'
import { getDefaultMiddlewareMatcher } from '../shared/lib/router/utils/get-default-middleware-matcher'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import type { ServerRuntime } from '../types'
......@@ -901,7 +900,7 @@ export async function createEntrypoints(
if (isMiddlewareFile(page)) {
middlewareMatchers = staticInfo.middleware?.matchers ?? [
getDefaultMiddlewareMatcher(params.config),
{ regexp: '.*', originalSource: '/:path*' },
]
}
......
......@@ -151,7 +151,6 @@ import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { recursiveCopy } from '../lib/recursive-copy'
import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getDefaultMiddlewareMatcher } from '../shared/lib/router/utils/get-default-middleware-matcher'
import { getFilesInDir } from '../lib/get-files-in-dir'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
......@@ -2585,7 +2584,10 @@ export default async function build(
functionsConfigManifest.functions['/_middleware'] = {
runtime: staticInfo.runtime,
matchers: staticInfo.middleware?.matchers ?? [
getDefaultMiddlewareMatcher(config),
{
regexp: '^.*$',
originalSource: '/:path*',
},
],
}
......
......@@ -2081,7 +2081,6 @@ export default async function getBaseWebpackConfig(
dev,
sriEnabled: !dev && !!config.experimental.sri?.algorithm,
rewrites,
nextConfig: config,
edgeEnvironments: {
__NEXT_BUILD_ID: buildId,
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: encryptionKey,
......
......@@ -5,7 +5,6 @@ import type {
import type { EdgeSSRMeta } from '../loaders/get-module-build-info'
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import { getNamedMiddlewareRegex } from '../../../shared/lib/router/utils/route-regex'
import { getDefaultMiddlewareMatcher } from '../../../shared/lib/router/utils/get-default-middleware-matcher'
import { getModuleBuildInfo } from '../loaders/get-module-build-info'
import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
......@@ -37,7 +36,6 @@ import type { CustomRoutes } from '../../../lib/load-custom-routes'
import { isInterceptionRouteRewrite } from '../../../lib/generate-interception-routes-rewrites'
import { getDynamicCodeEvaluationError } from './wellknown-errors-plugin/parse-dynamic-code-evaluation-error'
import { getModuleReferencesInOrder } from '../utils'
import type { NextConfigComplete } from '../../../server/config-shared'
const KNOWN_SAFE_DYNAMIC_PACKAGES =
require('../../../lib/known-edge-safe-packages.json') as string[]
......@@ -197,29 +195,21 @@ function getCreateAssets(params: {
continue
}
let matchers: MiddlewareMatcher[]
if (metadata?.edgeMiddleware?.matchers) {
matchers = metadata.edgeMiddleware.matchers
} else {
// For middleware at root with no explicit matchers, use getDefaultMiddlewareMatcher
// which respects skipMiddlewareNextInternalRoutes config
const catchAll = !metadata.edgeSSR && !metadata.edgeApiFunction
if (page === '/' && catchAll) {
matchers = [getDefaultMiddlewareMatcher(opts.nextConfig)]
} else {
const matcherSource = metadata.edgeSSR?.isAppDir
? normalizeAppPath(page)
: page
matchers = [
{
regexp: getNamedMiddlewareRegex(matcherSource, {
catchAll,
}).namedRegex,
originalSource: matcherSource,
},
]
}
}
const matcherSource = metadata.edgeSSR?.isAppDir
? normalizeAppPath(page)
: page
const catchAll = !metadata.edgeSSR && !metadata.edgeApiFunction
const { namedRegex } = getNamedMiddlewareRegex(matcherSource, {
catchAll,
})
const matchers = metadata?.edgeMiddleware?.matchers ?? [
{
regexp: namedRegex,
originalSource: page === '/' && catchAll ? '/:path*' : matcherSource,
},
]
const isEdgeFunction = !!(metadata.edgeApiFunction || metadata.edgeSSR)
const edgeFunctionDefinition: EdgeFunctionDefinition = {
......@@ -828,7 +818,6 @@ interface Options {
sriEnabled: boolean
rewrites: CustomRoutes['rewrites']
edgeEnvironments: EdgeRuntimeEnvironments
nextConfig: NextConfigComplete
}
export default class MiddlewarePlugin {
......@@ -836,20 +825,12 @@ export default class MiddlewarePlugin {
private readonly sriEnabled: Options['sriEnabled']
private readonly rewrites: Options['rewrites']
private readonly edgeEnvironments: EdgeRuntimeEnvironments
private readonly nextConfig: Options['nextConfig']
constructor({
dev,
sriEnabled,
rewrites,
edgeEnvironments,
nextConfig,
}: Options) {
constructor({ dev, sriEnabled, rewrites, edgeEnvironments }: Options) {
this.dev = dev
this.sriEnabled = sriEnabled
this.rewrites = rewrites
this.edgeEnvironments = edgeEnvironments
this.nextConfig = nextConfig
}
public apply(compiler: webpack.Compiler) {
......@@ -905,7 +886,6 @@ export default class MiddlewarePlugin {
rewrites: this.rewrites,
edgeEnvironments: this.edgeEnvironments,
dev: this.dev,
nextConfig: this.nextConfig,
},
})
)
......
......@@ -669,7 +669,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(),
serverExternalPackages: z.array(z.string()).optional(),
skipMiddlewareUrlNormalize: z.boolean().optional(),
skipMiddlewareNextInternalRoutes: z.boolean().optional(),
skipTrailingSlashRedirect: z.boolean().optional(),
staticPageGenerationTimeout: z.number().optional(),
expireTime: z.number().optional(),
......
......@@ -1228,12 +1228,6 @@ export interface NextConfig {
skipMiddlewareUrlNormalize?: boolean
/**
* Skip Next.js internals route `/_next` from middleware.
* @default true
*/
skipMiddlewareNextInternalRoutes?: boolean
skipTrailingSlashRedirect?: boolean
modularizeImports?: Record<
......@@ -1507,7 +1501,6 @@ export const defaultConfig = Object.freeze({
},
htmlLimitedBots: undefined,
bundlePagesRouterDependencies: false,
skipMiddlewareNextInternalRoutes: true,
} satisfies NextConfig)
export async function normalizeConfig(phase: string, config: any) {
......
......@@ -31,7 +31,6 @@ import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
import { getDefaultMiddlewareMatcher } from '../../../shared/lib/router/utils/get-default-middleware-matcher'
import {
APP_PATH_ROUTES_MANIFEST,
BUILD_ID_FILE,
......@@ -315,7 +314,7 @@ export async function setupFsCheck(opts: {
} else if (functionsConfigManifest?.functions['/_middleware']) {
middlewareMatcher = getMiddlewareRouteMatcher(
functionsConfigManifest.functions['/_middleware'].matchers ?? [
getDefaultMiddlewareMatcher(opts.config),
{ regexp: '.*', originalSource: '/:path*' },
]
)
}
......
......@@ -48,7 +48,6 @@ import {
} from '../../../shared/lib/constants'
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
import { getDefaultMiddlewareMatcher } from '../../../shared/lib/router/utils/get-default-middleware-matcher'
import {
isMiddlewareFile,
......@@ -501,7 +500,7 @@ async function startWatcher(
serverFields.actualMiddlewareFile
)
middlewareMatchers = staticInfo.middleware?.matchers || [
getDefaultMiddlewareMatcher(opts.nextConfig),
{ regexp: '^/.*$', originalSource: '/:path*' },
]
continue
}
......
......@@ -71,7 +71,6 @@ import type { LoadComponentsReturnType } from './load-components'
import isError, { getProperError } from '../lib/is-error'
import { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils'
import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'
import { getDefaultMiddlewareMatcher } from '../shared/lib/router/utils/get-default-middleware-matcher'
import { loadEnvConfig } from '@next/env'
import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
......@@ -1456,13 +1455,13 @@ export default class NextNodeServer extends BaseServer<
const middlewareModule = await this.loadNodeMiddleware()
if (middlewareModule) {
const matchers = middlewareModule.config?.matchers || [
getDefaultMiddlewareMatcher(this.nextConfig),
]
return {
match: getMiddlewareRouteMatcher(matchers),
match: getMiddlewareRouteMatcher(
middlewareModule.config?.matchers || [
{ regexp: '.*', originalSource: '/:path*' },
]
),
page: '/',
matchers,
}
}
......@@ -1472,7 +1471,6 @@ export default class NextNodeServer extends BaseServer<
return {
match: getMiddlewareMatcher(middleware),
page: '/',
matchers: middleware.matchers,
}
}
......
import type { NextConfig } from '../../../../types'
import type { MiddlewareMatcher } from '../../../../build/analysis/get-page-static-info'
export function getDefaultMiddlewareMatcher({
skipMiddlewareNextInternalRoutes,
}: NextConfig): MiddlewareMatcher {
if (skipMiddlewareNextInternalRoutes !== false) {
// Skip "/_next/" internal routes, except for "/_next/data/" which is needed for
// client-side navigation. Do not consider basePath as the user cannot create a
// route starts with underscore.
return {
regexp: '^(?!.*\\/\\_next\\/(?!data\\/)).*',
originalSource: '/((?!_next/(?!data/))[^]*)*',
}
}
return {
regexp: '^/.*$',
originalSource: '/:path*',
}
}
......@@ -39,8 +39,6 @@ describe('Middleware Runtime', () => {
),
},
nextConfig: {
// This test needs to intercept internal routes /_next/ (skipped by default)
skipMiddlewareNextInternalRoutes: false,
experimental: {
webpackBuildWorker: true,
},
......@@ -129,7 +127,7 @@ describe('Middleware Runtime', () => {
runtime: 'nodejs',
matchers: [
{
regexp: '^/.*$',
regexp: '^.*$',
originalSource: '/:path*',
},
],
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('middleware skip Next.js internal routes with base path', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should execute middleware on regular routes', async () => {
const res = await next.fetch('/base')
expect(res.status).toBe(200)
expect(res.headers.get('x-middleware-executed')).toBe('true')
})
it('should NOT execute middleware on _next routes', async () => {
const res = await next.fetch('/base/_next/static/chunks/webpack.js')
expect(res.headers.get('x-middleware-executed')).toBeFalsy()
})
})
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.headers.set('x-middleware-executed', 'true')
return response
}
/** @type {import('next').NextConfig} */
const nextConfig = {
basePath: '/base',
}
module.exports = nextConfig
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('middleware skip Next.js internal routes (opt-out)', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should execute middleware on regular routes', async () => {
const res = await next.fetch('/')
expect(res.status).toBe(200)
expect(res.headers.get('x-middleware-executed')).toBe('true')
})
it('should ALSO execute middleware on _next routes when opted out', async () => {
const res = await next.fetch('/_next/static/chunks/webpack.js')
expect(res.headers.get('x-middleware-executed')).toBe('true')
})
})
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.headers.set('x-middleware-executed', 'true')
return response
}
/** @type {import('next').NextConfig} */
const nextConfig = {
skipMiddlewareNextInternalRoutes: false,
}
module.exports = nextConfig
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('middleware skip Next.js internal routes', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should execute middleware on regular routes', async () => {
const res = await next.fetch('/')
expect(res.status).toBe(200)
expect(res.headers.get('x-middleware-executed')).toBe('true')
})
it('should NOT execute middleware on _next routes', async () => {
const res = await next.fetch('/_next/static/chunks/webpack.js')
expect(res.headers.get('x-middleware-executed')).toBeFalsy()
})
})
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.headers.set('x-middleware-executed', 'true')
return response
}
/** @type {import('next').NextConfig} */
const nextConfig = {}
module.exports = nextConfig
module.exports = {
// This test needs to intercept internal routes /_next/ (skipped by default)
skipMiddlewareNextInternalRoutes: false,
trailingSlash: true,
redirects() {
return [
......
/** @type {import('next').NextConfig} */
const nextConfig = {
// This test needs to intercept internal routes /_next/ (skipped by default)
skipMiddlewareNextInternalRoutes: false,
skipMiddlewareUrlNormalize: true,
skipTrailingSlashRedirect: true,
experimental: {
......
module.exports = {
// This test needs to intercept internal routes /_next/ (skipped by default)
skipMiddlewareNextInternalRoutes: false,
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment