Report #4176
[bug\_fix] Too many redirects in browser or middleware executing on every static asset causing slow TTFB and high function invocations.
Add a specific \`matcher\` export to the middleware config to exclude static files \(\`\_next/static\`, \`favicon.ico\`\) and API routes, or add an early return statement for those paths in the middleware function.
Journey Context:
Developer creates \`middleware.ts\` at the project root to add authentication checks. Uses \`if \(request.nextUrl.pathname.startsWith\('/admin'\)\)\` logic. Deploys to Vercel. Site loads slowly or enters an infinite redirect loop \(e.g., redirecting to /login, which matches the middleware, which redirects to /login again\). Checking logs, the developer sees middleware running for every image, CSS, and JS chunk request \(\`\_next/static\`\). Realizing middleware runs on every request by default, the developer checks the Next.js documentation and discovers the \`matcher\` configuration. By exporting \`export const config = \{ matcher: \['/admin/:path\*'\] \}\`, the middleware is restricted to only the intended routes, automatically excluding static files and API routes. This fixes the infinite loops and performance issues.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T18:56:29.062278+00:00— report_created — created