@@ -16,6 +16,7 @@ import { join as posixJoin, sep as posixSep } from 'node:path/posix'
1616import { trace } from '@opentelemetry/api'
1717import { wrapTracer } from '@opentelemetry/api/experimental'
1818import glob from 'fast-glob'
19+ import type { MiddlewareManifest } from 'next/dist/build/webpack/plugins/middleware-plugin.js'
1920import { prerelease , satisfies , lt as semverLowerThan , lte as semverLowerThanOrEqual } from 'semver'
2021
2122import type { RunConfig } from '../../run/config.js'
@@ -324,23 +325,44 @@ export const copyNextDependencies = async (ctx: PluginContext): Promise<void> =>
324325}
325326
326327/**
327- * Generates a copy of the middleware manifest without any middleware in it . We
328+ * Generates a copy of the middleware manifest that make all matchers never match on anything . We
328329 * do this because we'll run middleware in an edge function, and we don't want
329- * to run it again in the server handler.
330+ * to run it again in the server handler. Additionally Next.js conditionally enable some handling
331+ * depending if there is a middleware present, so we need to keep reference to middleware in server
332+ * even if we don't actually want to ever run it there.
330333 */
331334const replaceMiddlewareManifest = async ( sourcePath : string , destPath : string ) => {
332335 await mkdir ( dirname ( destPath ) , { recursive : true } )
333336
334337 const data = await readFile ( sourcePath , 'utf8' )
335- const manifest = JSON . parse ( data )
338+ const manifest = JSON . parse ( data ) as MiddlewareManifest
336339
337340 // TODO: Check for `manifest.version` and write an error to the system log
338341 // when we find a value that is not equal to 2. This will alert us in case
339342 // Next.js starts using a new format for the manifest and we're writing
340343 // one with the old version.
341344 const newManifest = {
342345 ...manifest ,
343- middleware : { } ,
346+ middleware : Object . fromEntries (
347+ Object . entries ( manifest . middleware ) . map ( ( [ key , edgeFunctionDefinition ] ) => {
348+ return [
349+ key ,
350+ {
351+ ...edgeFunctionDefinition ,
352+ matchers : edgeFunctionDefinition . matchers . map ( ( matcher ) => {
353+ return {
354+ ...matcher ,
355+ // matcher that won't match on anything
356+ // this is meant to disable actually running middleware in the server handler,
357+ // while still allowing next server to enable some middleware specific handling
358+ // such as _next/data normalization ( https://github.com/vercel/next.js/blob/7bb72e508572237fe0d4aac5418546d4b4b3a363/packages/next/src/server/lib/router-utils/resolve-routes.ts#L395 )
359+ regexp : '(?!.*)' ,
360+ }
361+ } ) ,
362+ } ,
363+ ]
364+ } ) ,
365+ ) ,
344366 }
345367 const newData = JSON . stringify ( newManifest )
346368
0 commit comments