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::{ ...@@ -42,31 +42,6 @@ use crate::{
route::{Endpoint, EndpointOutput, EndpointOutputPaths}, 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] #[turbo_tasks::value]
pub struct MiddlewareEndpoint { pub struct MiddlewareEndpoint {
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
...@@ -190,8 +165,6 @@ impl MiddlewareEndpoint { ...@@ -190,8 +165,6 @@ impl MiddlewareEndpoint {
.map(|i18n| i18n.locales.len() > 1) .map(|i18n| i18n.locales.len() > 1)
.unwrap_or(false); .unwrap_or(false);
let base_path = next_config.base_path().await?; 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() { let matchers = if let Some(matchers) = config.middleware_matcher.as_ref() {
matchers matchers
...@@ -243,9 +216,11 @@ impl MiddlewareEndpoint { ...@@ -243,9 +216,11 @@ impl MiddlewareEndpoint {
}) })
.collect() .collect()
} else { } else {
vec![get_default_middleware_matcher( vec![MiddlewareMatcher {
*skip_middleware_next_internal_routes, regexp: Some(rcstr!("^/.*$")),
)] original_source: rcstr!("/:path*"),
..Default::default()
}]
}; };
if matches!(runtime, NextRuntime::NodeJs) { if matches!(runtime, NextRuntime::NodeJs) {
......
...@@ -103,7 +103,6 @@ pub struct NextConfig { ...@@ -103,7 +103,6 @@ pub struct NextConfig {
asset_prefix: Option<RcStr>, asset_prefix: Option<RcStr>,
base_path: Option<RcStr>, base_path: Option<RcStr>,
skip_middleware_url_normalize: Option<bool>, skip_middleware_url_normalize: Option<bool>,
skip_middleware_next_internal_routes: 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>,
...@@ -1344,11 +1343,6 @@ impl NextConfig { ...@@ -1344,11 +1343,6 @@ impl NextConfig {
Vc::cell(self.base_path.clone()) 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] #[turbo_tasks::function]
pub fn cache_handler(&self, project_path: FileSystemPath) -> Result<Vc<OptionFileSystemPath>> { pub fn cache_handler(&self, project_path: FileSystemPath) -> Result<Vc<OptionFileSystemPath>> {
if let Some(handler) = &self.cache_handler { if let Some(handler) = &self.cache_handler {
......
...@@ -47,7 +47,6 @@ import { ...@@ -47,7 +47,6 @@ import {
isInstrumentationHookFilename, isInstrumentationHookFilename,
} from './utils' } from './utils'
import { getPageStaticInfo } from './analysis/get-page-static-info' 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 { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import type { ServerRuntime } from '../types' import type { ServerRuntime } from '../types'
...@@ -901,7 +900,7 @@ export async function createEntrypoints( ...@@ -901,7 +900,7 @@ export async function createEntrypoints(
if (isMiddlewareFile(page)) { if (isMiddlewareFile(page)) {
middlewareMatchers = staticInfo.middleware?.matchers ?? [ middlewareMatchers = staticInfo.middleware?.matchers ?? [
getDefaultMiddlewareMatcher(params.config), { regexp: '.*', originalSource: '/:path*' },
] ]
} }
......
...@@ -151,7 +151,6 @@ import { isEdgeRuntime } from '../lib/is-edge-runtime' ...@@ -151,7 +151,6 @@ import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { recursiveCopy } from '../lib/recursive-copy' import { recursiveCopy } from '../lib/recursive-copy'
import { lockfilePatchPromise, teardownTraceSubscriber } from './swc' import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' 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 { getFilesInDir } from '../lib/get-files-in-dir'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins' import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
...@@ -2585,7 +2584,10 @@ export default async function build( ...@@ -2585,7 +2584,10 @@ export default async function build(
functionsConfigManifest.functions['/_middleware'] = { functionsConfigManifest.functions['/_middleware'] = {
runtime: staticInfo.runtime, runtime: staticInfo.runtime,
matchers: staticInfo.middleware?.matchers ?? [ matchers: staticInfo.middleware?.matchers ?? [
getDefaultMiddlewareMatcher(config), {
regexp: '^.*$',
originalSource: '/:path*',
},
], ],
} }
......
...@@ -2081,7 +2081,6 @@ export default async function getBaseWebpackConfig( ...@@ -2081,7 +2081,6 @@ export default async function getBaseWebpackConfig(
dev, dev,
sriEnabled: !dev && !!config.experimental.sri?.algorithm, sriEnabled: !dev && !!config.experimental.sri?.algorithm,
rewrites, rewrites,
nextConfig: config,
edgeEnvironments: { edgeEnvironments: {
__NEXT_BUILD_ID: buildId, __NEXT_BUILD_ID: buildId,
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: encryptionKey, NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: encryptionKey,
......
...@@ -5,7 +5,6 @@ import type { ...@@ -5,7 +5,6 @@ import type {
import type { EdgeSSRMeta } from '../loaders/get-module-build-info' import type { EdgeSSRMeta } from '../loaders/get-module-build-info'
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info' import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import { getNamedMiddlewareRegex } from '../../../shared/lib/router/utils/route-regex' 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 { getModuleBuildInfo } from '../loaders/get-module-build-info'
import { getSortedRoutes } from '../../../shared/lib/router/utils' import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
...@@ -37,7 +36,6 @@ import type { CustomRoutes } from '../../../lib/load-custom-routes' ...@@ -37,7 +36,6 @@ import type { CustomRoutes } from '../../../lib/load-custom-routes'
import { isInterceptionRouteRewrite } from '../../../lib/generate-interception-routes-rewrites' import { isInterceptionRouteRewrite } from '../../../lib/generate-interception-routes-rewrites'
import { getDynamicCodeEvaluationError } from './wellknown-errors-plugin/parse-dynamic-code-evaluation-error' import { getDynamicCodeEvaluationError } from './wellknown-errors-plugin/parse-dynamic-code-evaluation-error'
import { getModuleReferencesInOrder } from '../utils' import { getModuleReferencesInOrder } from '../utils'
import type { NextConfigComplete } from '../../../server/config-shared'
const KNOWN_SAFE_DYNAMIC_PACKAGES = const KNOWN_SAFE_DYNAMIC_PACKAGES =
require('../../../lib/known-edge-safe-packages.json') as string[] require('../../../lib/known-edge-safe-packages.json') as string[]
...@@ -197,29 +195,21 @@ function getCreateAssets(params: { ...@@ -197,29 +195,21 @@ function getCreateAssets(params: {
continue continue
} }
let matchers: MiddlewareMatcher[] const matcherSource = metadata.edgeSSR?.isAppDir
if (metadata?.edgeMiddleware?.matchers) { ? normalizeAppPath(page)
matchers = metadata.edgeMiddleware.matchers : page
} else {
// For middleware at root with no explicit matchers, use getDefaultMiddlewareMatcher const catchAll = !metadata.edgeSSR && !metadata.edgeApiFunction
// which respects skipMiddlewareNextInternalRoutes config
const catchAll = !metadata.edgeSSR && !metadata.edgeApiFunction const { namedRegex } = getNamedMiddlewareRegex(matcherSource, {
if (page === '/' && catchAll) { catchAll,
matchers = [getDefaultMiddlewareMatcher(opts.nextConfig)] })
} else { const matchers = metadata?.edgeMiddleware?.matchers ?? [
const matcherSource = metadata.edgeSSR?.isAppDir {
? normalizeAppPath(page) regexp: namedRegex,
: page originalSource: page === '/' && catchAll ? '/:path*' : matcherSource,
matchers = [ },
{ ]
regexp: getNamedMiddlewareRegex(matcherSource, {
catchAll,
}).namedRegex,
originalSource: matcherSource,
},
]
}
}
const isEdgeFunction = !!(metadata.edgeApiFunction || metadata.edgeSSR) const isEdgeFunction = !!(metadata.edgeApiFunction || metadata.edgeSSR)
const edgeFunctionDefinition: EdgeFunctionDefinition = { const edgeFunctionDefinition: EdgeFunctionDefinition = {
...@@ -828,7 +818,6 @@ interface Options { ...@@ -828,7 +818,6 @@ interface Options {
sriEnabled: boolean sriEnabled: boolean
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
edgeEnvironments: EdgeRuntimeEnvironments edgeEnvironments: EdgeRuntimeEnvironments
nextConfig: NextConfigComplete
} }
export default class MiddlewarePlugin { export default class MiddlewarePlugin {
...@@ -836,20 +825,12 @@ export default class MiddlewarePlugin { ...@@ -836,20 +825,12 @@ export default class MiddlewarePlugin {
private readonly sriEnabled: Options['sriEnabled'] private readonly sriEnabled: Options['sriEnabled']
private readonly rewrites: Options['rewrites'] private readonly rewrites: Options['rewrites']
private readonly edgeEnvironments: EdgeRuntimeEnvironments private readonly edgeEnvironments: EdgeRuntimeEnvironments
private readonly nextConfig: Options['nextConfig']
constructor({ dev, sriEnabled, rewrites, edgeEnvironments }: Options) {
constructor({
dev,
sriEnabled,
rewrites,
edgeEnvironments,
nextConfig,
}: Options) {
this.dev = dev this.dev = dev
this.sriEnabled = sriEnabled this.sriEnabled = sriEnabled
this.rewrites = rewrites this.rewrites = rewrites
this.edgeEnvironments = edgeEnvironments this.edgeEnvironments = edgeEnvironments
this.nextConfig = nextConfig
} }
public apply(compiler: webpack.Compiler) { public apply(compiler: webpack.Compiler) {
...@@ -905,7 +886,6 @@ export default class MiddlewarePlugin { ...@@ -905,7 +886,6 @@ export default class MiddlewarePlugin {
rewrites: this.rewrites, rewrites: this.rewrites,
edgeEnvironments: this.edgeEnvironments, edgeEnvironments: this.edgeEnvironments,
dev: this.dev, dev: this.dev,
nextConfig: this.nextConfig,
}, },
}) })
) )
......
...@@ -669,7 +669,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -669,7 +669,6 @@ 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(),
skipMiddlewareNextInternalRoutes: 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(),
......
...@@ -1228,12 +1228,6 @@ export interface NextConfig { ...@@ -1228,12 +1228,6 @@ export interface NextConfig {
skipMiddlewareUrlNormalize?: boolean skipMiddlewareUrlNormalize?: boolean
/**
* Skip Next.js internals route `/_next` from middleware.
* @default true
*/
skipMiddlewareNextInternalRoutes?: boolean
skipTrailingSlashRedirect?: boolean skipTrailingSlashRedirect?: boolean
modularizeImports?: Record< modularizeImports?: Record<
...@@ -1507,7 +1501,6 @@ export const defaultConfig = Object.freeze({ ...@@ -1507,7 +1501,6 @@ export const defaultConfig = Object.freeze({
}, },
htmlLimitedBots: undefined, htmlLimitedBots: undefined,
bundlePagesRouterDependencies: false, bundlePagesRouterDependencies: false,
skipMiddlewareNextInternalRoutes: true,
} satisfies NextConfig) } satisfies NextConfig)
export async function normalizeConfig(phase: string, config: any) { export async function normalizeConfig(phase: string, config: any) {
......
...@@ -31,7 +31,6 @@ import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix' ...@@ -31,7 +31,6 @@ import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
import { getDefaultMiddlewareMatcher } from '../../../shared/lib/router/utils/get-default-middleware-matcher'
import { import {
APP_PATH_ROUTES_MANIFEST, APP_PATH_ROUTES_MANIFEST,
BUILD_ID_FILE, BUILD_ID_FILE,
...@@ -315,7 +314,7 @@ export async function setupFsCheck(opts: { ...@@ -315,7 +314,7 @@ export async function setupFsCheck(opts: {
} else if (functionsConfigManifest?.functions['/_middleware']) { } else if (functionsConfigManifest?.functions['/_middleware']) {
middlewareMatcher = getMiddlewareRouteMatcher( middlewareMatcher = getMiddlewareRouteMatcher(
functionsConfigManifest.functions['/_middleware'].matchers ?? [ functionsConfigManifest.functions['/_middleware'].matchers ?? [
getDefaultMiddlewareMatcher(opts.config), { regexp: '.*', originalSource: '/:path*' },
] ]
) )
} }
......
...@@ -48,7 +48,6 @@ import { ...@@ -48,7 +48,6 @@ import {
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
import { getDefaultMiddlewareMatcher } from '../../../shared/lib/router/utils/get-default-middleware-matcher'
import { import {
isMiddlewareFile, isMiddlewareFile,
...@@ -501,7 +500,7 @@ async function startWatcher( ...@@ -501,7 +500,7 @@ async function startWatcher(
serverFields.actualMiddlewareFile serverFields.actualMiddlewareFile
) )
middlewareMatchers = staticInfo.middleware?.matchers || [ middlewareMatchers = staticInfo.middleware?.matchers || [
getDefaultMiddlewareMatcher(opts.nextConfig), { regexp: '^/.*$', originalSource: '/:path*' },
] ]
continue continue
} }
......
...@@ -71,7 +71,6 @@ import type { LoadComponentsReturnType } from './load-components' ...@@ -71,7 +71,6 @@ import type { LoadComponentsReturnType } from './load-components'
import isError, { getProperError } from '../lib/is-error' import isError, { getProperError } from '../lib/is-error'
import { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils' import { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils'
import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher' 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 { loadEnvConfig } from '@next/env'
import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring' import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
...@@ -1456,13 +1455,13 @@ export default class NextNodeServer extends BaseServer< ...@@ -1456,13 +1455,13 @@ export default class NextNodeServer extends BaseServer<
const middlewareModule = await this.loadNodeMiddleware() const middlewareModule = await this.loadNodeMiddleware()
if (middlewareModule) { if (middlewareModule) {
const matchers = middlewareModule.config?.matchers || [
getDefaultMiddlewareMatcher(this.nextConfig),
]
return { return {
match: getMiddlewareRouteMatcher(matchers), match: getMiddlewareRouteMatcher(
middlewareModule.config?.matchers || [
{ regexp: '.*', originalSource: '/:path*' },
]
),
page: '/', page: '/',
matchers,
} }
} }
...@@ -1472,7 +1471,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -1472,7 +1471,6 @@ export default class NextNodeServer extends BaseServer<
return { return {
match: getMiddlewareMatcher(middleware), match: getMiddlewareMatcher(middleware),
page: '/', 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', () => { ...@@ -39,8 +39,6 @@ describe('Middleware Runtime', () => {
), ),
}, },
nextConfig: { nextConfig: {
// This test needs to intercept internal routes /_next/ (skipped by default)
skipMiddlewareNextInternalRoutes: false,
experimental: { experimental: {
webpackBuildWorker: true, webpackBuildWorker: true,
}, },
...@@ -129,7 +127,7 @@ describe('Middleware Runtime', () => { ...@@ -129,7 +127,7 @@ describe('Middleware Runtime', () => {
runtime: 'nodejs', runtime: 'nodejs',
matchers: [ matchers: [
{ {
regexp: '^/.*$', regexp: '^.*$',
originalSource: '/:path*', 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 = { module.exports = {
// This test needs to intercept internal routes /_next/ (skipped by default)
skipMiddlewareNextInternalRoutes: false,
trailingSlash: true, trailingSlash: true,
redirects() { redirects() {
return [ return [
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
// This test needs to intercept internal routes /_next/ (skipped by default)
skipMiddlewareNextInternalRoutes: false,
skipMiddlewareUrlNormalize: true, skipMiddlewareUrlNormalize: true,
skipTrailingSlashRedirect: true, skipTrailingSlashRedirect: true,
experimental: { 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