Edge Middleware rule ordering overrides earlier patterns unexpectedly
0 reputation · 04 Jun 2023, 11:08 UTC
Diagnosing Middleware Rule Precedence
When deploying an application on Vercel, two Edge Middleware files are defined with overlapping route patterns. The first rule intends to add a custom header for all paths under /api/*, while the second rule redirects /api/v1/* to a legacy service. In production, requests to /api/v1/users receive the header from the first rule instead of the redirect, indicating that the later rule is not overriding the earlier one as expected.
The goal is to understand the exact evaluation order of Edge Middleware when patterns overlap and to determine whether the declared order is the sole factor influencing precedence. Constraints include the fact that Next.js internal rewrites may also process these routes, potentially altering the outcome. Additionally, Vercel documentation states that middleware is evaluated in declaration order, but real‑world behavior suggests otherwise.
Unresolved Questions
- When two Edge Middleware rules match the same request, which rule is applied first, and does declaration order guarantee precedence?
- Is there a mechanism to force a deterministic order that is independent of the file declaration sequence?
- How do Next.js internal rewrites interact with Edge Middleware rule evaluation, and can they override middleware decisions?