@@ -12,14 +12,20 @@ export interface MiddlewareRouteMatch {
12
12
}
13
13
14
14
export function getMiddlewareRouteMatcher (
15
- matchers : MiddlewareMatcher [ ]
15
+ matchers : MiddlewareMatcher [ ] ,
16
+ skipMiddlewareNextInternalRoutes : boolean
16
17
) : MiddlewareRouteMatch {
18
+ // Apply exclusion logic to matchers if needed
19
+ const processedMatchers = skipMiddlewareNextInternalRoutes
20
+ ? excludeNextInternalRoutesFromMatchers ( matchers )
21
+ : matchers
22
+
17
23
return (
18
24
pathname : string | null | undefined ,
19
25
req : BaseNextRequest ,
20
26
query : Params
21
27
) => {
22
- for ( const matcher of matchers ) {
28
+ for ( const matcher of processedMatchers ) {
23
29
const routeMatch = new RegExp ( matcher . regexp ) . exec ( pathname ! )
24
30
if ( ! routeMatch ) {
25
31
continue
@@ -38,3 +44,28 @@ export function getMiddlewareRouteMatcher(
38
44
return false
39
45
}
40
46
}
47
+
48
+ function excludeNextInternalRoutesFromMatchers ( matchers : MiddlewareMatcher [ ] ) {
49
+ return matchers . map ( ( matcher ) => {
50
+ // If the matcher explicitly targets _next, don't modify it
51
+ if ( matcher . originalSource ?. includes ( '/_next/' ) ) {
52
+ return matcher
53
+ }
54
+
55
+ // Modify the regex to exclude _next routes
56
+ let modifiedRegex = matcher . regexp
57
+
58
+ // If the regex starts with ^, insert negative lookahead after it
59
+ if ( modifiedRegex . startsWith ( '^' ) ) {
60
+ modifiedRegex = `^(?!.*/_next/)${ modifiedRegex . slice ( 1 ) } `
61
+ } else {
62
+ // Otherwise, add negative lookahead at the beginning
63
+ modifiedRegex = `(?!.*/_next/)${ modifiedRegex } `
64
+ }
65
+
66
+ return {
67
+ ...matcher ,
68
+ regexp : modifiedRegex ,
69
+ }
70
+ } )
71
+ }
0 commit comments