Middleware matcher leaves prefetched protected routes publicly accessible
0 reputation · 22 Jun 2024, 10:13 UTC
In a Next.js App Router project (version 13 or later) using Middleware for centralized authentication, the goal is to guarantee that routes under a protected prefix such as /dashboard are never reachable without a valid session. The matcher configuration is intended to scope the security check to those paths, while the Edge Runtime restricts certain Node.js APIs during token verification.
The uncertainty lies in how the Next.js Router Cache and automatic prefetching interact with Middleware redirects. If a protected page is prefetched or cached on the client before authentication is checked, the redirect may not fire as expected, leaving the route accidentally public. Static assets under /public are also documented to bypass Middleware entirely, which complicates assumptions about blanket protection.
This raises an unresolved design decision about where to enforce the boundary. Should the matcher be narrowed to exclude prefetchable RSC requests, or should protection be duplicated in Server Components and route handlers? How does the documented behavior of the Router Cache affect the reliability of a Middleware-only redirect for protected App Router routes, and what verification steps confirm that no public path remains accessible?