Skip to content

Commit 0b5c649

Browse files
authored
Revert "[Breaking] Skip Next.js internal routes /_next in middleware (#84239)"
This reverts commit 6b72050.
1 parent 954d40b commit 0b5c649

File tree

31 files changed

+35
-262
lines changed

31 files changed

+35
-262
lines changed

crates/next-api/src/middleware.rs

Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -42,31 +42,6 @@ use crate::{
4242
route::{Endpoint, EndpointOutput, EndpointOutputPaths},
4343
};
4444

45-
/// Rust implementation of the TypeScript getDefaultMiddlewareMatcher function
46-
/// Generates default middleware matcher patterns that respect skipMiddlewareNextInternalRoutes
47-
fn get_default_middleware_matcher(
48-
skip_middleware_next_internal_routes: Option<bool>,
49-
) -> MiddlewareMatcher {
50-
let skip_internal = skip_middleware_next_internal_routes.unwrap_or(true);
51-
52-
if skip_internal {
53-
// Skip "/_next/" internal routes, except for "/_next/data/" which is needed for
54-
// client-side navigation. Do not consider basePath as the user cannot create a
55-
// route starts with underscore.
56-
MiddlewareMatcher {
57-
regexp: Some(rcstr!("^(?!.*\\/\\_next\\/(?!data\\/)).*")),
58-
original_source: rcstr!("/((?!_next/(?!data/))[^]*)*"),
59-
..Default::default()
60-
}
61-
} else {
62-
MiddlewareMatcher {
63-
regexp: Some(rcstr!("^/.*$")),
64-
original_source: rcstr!("/:path*"),
65-
..Default::default()
66-
}
67-
}
68-
}
69-
7045
#[turbo_tasks::value]
7146
pub struct MiddlewareEndpoint {
7247
project: ResolvedVc<Project>,
@@ -190,8 +165,6 @@ impl MiddlewareEndpoint {
190165
.map(|i18n| i18n.locales.len() > 1)
191166
.unwrap_or(false);
192167
let base_path = next_config.base_path().await?;
193-
let skip_middleware_next_internal_routes =
194-
next_config.skip_middleware_next_internal_routes().await?;
195168

196169
let matchers = if let Some(matchers) = config.middleware_matcher.as_ref() {
197170
matchers
@@ -243,9 +216,11 @@ impl MiddlewareEndpoint {
243216
})
244217
.collect()
245218
} else {
246-
vec![get_default_middleware_matcher(
247-
*skip_middleware_next_internal_routes,
248-
)]
219+
vec![MiddlewareMatcher {
220+
regexp: Some(rcstr!("^/.*$")),
221+
original_source: rcstr!("/:path*"),
222+
..Default::default()
223+
}]
249224
};
250225

251226
if matches!(runtime, NextRuntime::NodeJs) {

crates/next-core/src/next_config.rs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,6 @@ pub struct NextConfig {
103103
asset_prefix: Option<RcStr>,
104104
base_path: Option<RcStr>,
105105
skip_middleware_url_normalize: Option<bool>,
106-
skip_middleware_next_internal_routes: Option<bool>,
107106
skip_trailing_slash_redirect: Option<bool>,
108107
i18n: Option<I18NConfig>,
109108
cross_origin: Option<CrossOriginConfig>,
@@ -1344,11 +1343,6 @@ impl NextConfig {
13441343
Vc::cell(self.base_path.clone())
13451344
}
13461345

1347-
#[turbo_tasks::function]
1348-
pub fn skip_middleware_next_internal_routes(&self) -> Vc<Option<bool>> {
1349-
Vc::cell(self.skip_middleware_next_internal_routes)
1350-
}
1351-
13521346
#[turbo_tasks::function]
13531347
pub fn cache_handler(&self, project_path: FileSystemPath) -> Result<Vc<OptionFileSystemPath>> {
13541348
if let Some(handler) = &self.cache_handler {

packages/next/src/build/entries.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ import {
4747
isInstrumentationHookFilename,
4848
} from './utils'
4949
import { getPageStaticInfo } from './analysis/get-page-static-info'
50-
import { getDefaultMiddlewareMatcher } from '../shared/lib/router/utils/get-default-middleware-matcher'
5150
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
5251
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
5352
import type { ServerRuntime } from '../types'
@@ -901,7 +900,7 @@ export async function createEntrypoints(
901900

902901
if (isMiddlewareFile(page)) {
903902
middlewareMatchers = staticInfo.middleware?.matchers ?? [
904-
getDefaultMiddlewareMatcher(params.config),
903+
{ regexp: '.*', originalSource: '/:path*' },
905904
]
906905
}
907906

packages/next/src/build/index.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,6 @@ import { isEdgeRuntime } from '../lib/is-edge-runtime'
151151
import { recursiveCopy } from '../lib/recursive-copy'
152152
import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
153153
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
154-
import { getDefaultMiddlewareMatcher } from '../shared/lib/router/utils/get-default-middleware-matcher'
155154
import { getFilesInDir } from '../lib/get-files-in-dir'
156155
import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
157156
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
@@ -2585,7 +2584,10 @@ export default async function build(
25852584
functionsConfigManifest.functions['/_middleware'] = {
25862585
runtime: staticInfo.runtime,
25872586
matchers: staticInfo.middleware?.matchers ?? [
2588-
getDefaultMiddlewareMatcher(config),
2587+
{
2588+
regexp: '^.*$',
2589+
originalSource: '/:path*',
2590+
},
25892591
],
25902592
}
25912593

packages/next/src/build/webpack-config.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2081,7 +2081,6 @@ export default async function getBaseWebpackConfig(
20812081
dev,
20822082
sriEnabled: !dev && !!config.experimental.sri?.algorithm,
20832083
rewrites,
2084-
nextConfig: config,
20852084
edgeEnvironments: {
20862085
__NEXT_BUILD_ID: buildId,
20872086
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: encryptionKey,

packages/next/src/build/webpack/plugins/middleware-plugin.ts

Lines changed: 17 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import type {
55
import type { EdgeSSRMeta } from '../loaders/get-module-build-info'
66
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
77
import { getNamedMiddlewareRegex } from '../../../shared/lib/router/utils/route-regex'
8-
import { getDefaultMiddlewareMatcher } from '../../../shared/lib/router/utils/get-default-middleware-matcher'
98
import { getModuleBuildInfo } from '../loaders/get-module-build-info'
109
import { getSortedRoutes } from '../../../shared/lib/router/utils'
1110
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
@@ -37,7 +36,6 @@ import type { CustomRoutes } from '../../../lib/load-custom-routes'
3736
import { isInterceptionRouteRewrite } from '../../../lib/generate-interception-routes-rewrites'
3837
import { getDynamicCodeEvaluationError } from './wellknown-errors-plugin/parse-dynamic-code-evaluation-error'
3938
import { getModuleReferencesInOrder } from '../utils'
40-
import type { NextConfigComplete } from '../../../server/config-shared'
4139

4240
const KNOWN_SAFE_DYNAMIC_PACKAGES =
4341
require('../../../lib/known-edge-safe-packages.json') as string[]
@@ -197,29 +195,21 @@ function getCreateAssets(params: {
197195
continue
198196
}
199197

200-
let matchers: MiddlewareMatcher[]
201-
if (metadata?.edgeMiddleware?.matchers) {
202-
matchers = metadata.edgeMiddleware.matchers
203-
} else {
204-
// For middleware at root with no explicit matchers, use getDefaultMiddlewareMatcher
205-
// which respects skipMiddlewareNextInternalRoutes config
206-
const catchAll = !metadata.edgeSSR && !metadata.edgeApiFunction
207-
if (page === '/' && catchAll) {
208-
matchers = [getDefaultMiddlewareMatcher(opts.nextConfig)]
209-
} else {
210-
const matcherSource = metadata.edgeSSR?.isAppDir
211-
? normalizeAppPath(page)
212-
: page
213-
matchers = [
214-
{
215-
regexp: getNamedMiddlewareRegex(matcherSource, {
216-
catchAll,
217-
}).namedRegex,
218-
originalSource: matcherSource,
219-
},
220-
]
221-
}
222-
}
198+
const matcherSource = metadata.edgeSSR?.isAppDir
199+
? normalizeAppPath(page)
200+
: page
201+
202+
const catchAll = !metadata.edgeSSR && !metadata.edgeApiFunction
203+
204+
const { namedRegex } = getNamedMiddlewareRegex(matcherSource, {
205+
catchAll,
206+
})
207+
const matchers = metadata?.edgeMiddleware?.matchers ?? [
208+
{
209+
regexp: namedRegex,
210+
originalSource: page === '/' && catchAll ? '/:path*' : matcherSource,
211+
},
212+
]
223213

224214
const isEdgeFunction = !!(metadata.edgeApiFunction || metadata.edgeSSR)
225215
const edgeFunctionDefinition: EdgeFunctionDefinition = {
@@ -828,28 +818,19 @@ interface Options {
828818
sriEnabled: boolean
829819
rewrites: CustomRoutes['rewrites']
830820
edgeEnvironments: EdgeRuntimeEnvironments
831-
nextConfig: NextConfigComplete
832821
}
833822

834823
export default class MiddlewarePlugin {
835824
private readonly dev: Options['dev']
836825
private readonly sriEnabled: Options['sriEnabled']
837826
private readonly rewrites: Options['rewrites']
838827
private readonly edgeEnvironments: EdgeRuntimeEnvironments
839-
private readonly nextConfig: Options['nextConfig']
840-
841-
constructor({
842-
dev,
843-
sriEnabled,
844-
rewrites,
845-
edgeEnvironments,
846-
nextConfig,
847-
}: Options) {
828+
829+
constructor({ dev, sriEnabled, rewrites, edgeEnvironments }: Options) {
848830
this.dev = dev
849831
this.sriEnabled = sriEnabled
850832
this.rewrites = rewrites
851833
this.edgeEnvironments = edgeEnvironments
852-
this.nextConfig = nextConfig
853834
}
854835

855836
public apply(compiler: webpack.Compiler) {
@@ -905,7 +886,6 @@ export default class MiddlewarePlugin {
905886
rewrites: this.rewrites,
906887
edgeEnvironments: this.edgeEnvironments,
907888
dev: this.dev,
908-
nextConfig: this.nextConfig,
909889
},
910890
})
911891
)

packages/next/src/server/config-schema.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -669,7 +669,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
669669
.optional(),
670670
serverExternalPackages: z.array(z.string()).optional(),
671671
skipMiddlewareUrlNormalize: z.boolean().optional(),
672-
skipMiddlewareNextInternalRoutes: z.boolean().optional(),
673672
skipTrailingSlashRedirect: z.boolean().optional(),
674673
staticPageGenerationTimeout: z.number().optional(),
675674
expireTime: z.number().optional(),

packages/next/src/server/config-shared.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1228,12 +1228,6 @@ export interface NextConfig {
12281228

12291229
skipMiddlewareUrlNormalize?: boolean
12301230

1231-
/**
1232-
* Skip Next.js internals route `/_next` from middleware.
1233-
* @default true
1234-
*/
1235-
skipMiddlewareNextInternalRoutes?: boolean
1236-
12371231
skipTrailingSlashRedirect?: boolean
12381232

12391233
modularizeImports?: Record<
@@ -1507,7 +1501,6 @@ export const defaultConfig = Object.freeze({
15071501
},
15081502
htmlLimitedBots: undefined,
15091503
bundlePagesRouterDependencies: false,
1510-
skipMiddlewareNextInternalRoutes: true,
15111504
} satisfies NextConfig)
15121505

15131506
export async function normalizeConfig(phase: string, config: any) {

packages/next/src/server/lib/router-utils/filesystem.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'
3131
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
3232
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
3333
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
34-
import { getDefaultMiddlewareMatcher } from '../../../shared/lib/router/utils/get-default-middleware-matcher'
3534
import {
3635
APP_PATH_ROUTES_MANIFEST,
3736
BUILD_ID_FILE,
@@ -315,7 +314,7 @@ export async function setupFsCheck(opts: {
315314
} else if (functionsConfigManifest?.functions['/_middleware']) {
316315
middlewareMatcher = getMiddlewareRouteMatcher(
317316
functionsConfigManifest.functions['/_middleware'].matchers ?? [
318-
getDefaultMiddlewareMatcher(opts.config),
317+
{ regexp: '.*', originalSource: '/:path*' },
319318
]
320319
)
321320
}

packages/next/src/server/lib/router-utils/setup-dev-bundler.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ import {
4848
} from '../../../shared/lib/constants'
4949

5050
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
51-
import { getDefaultMiddlewareMatcher } from '../../../shared/lib/router/utils/get-default-middleware-matcher'
5251

5352
import {
5453
isMiddlewareFile,
@@ -501,7 +500,7 @@ async function startWatcher(
501500
serverFields.actualMiddlewareFile
502501
)
503502
middlewareMatchers = staticInfo.middleware?.matchers || [
504-
getDefaultMiddlewareMatcher(opts.nextConfig),
503+
{ regexp: '^/.*$', originalSource: '/:path*' },
505504
]
506505
continue
507506
}

0 commit comments

Comments
 (0)