- Next.js
- Debugging & Production Anti-Patterns
- Network Interceptor Traps: Regex Catastrophes and Infinite Loops
Network Interceptor Traps: Regex Catastrophes and Infinite Loops
Network interceptors (middleware.ts and proxy.ts) execute before every HTTP request. Fatal production anti-patterns include: 1) Flawed matcher regexes that intercept internal static assets (/_next/static, favicon.ico), 2) Infinite redirect loops caused by redirecting to a route that triggers the same redirect condition, and 3) Catastrophic backtracking in poorly structured regular expressions (ReDoS).
Learning Objectives
Construct rock-solid middleware matcher regexes that cleanly exclude static assets.
Diagnose and break infinite redirect loops (ERR_TOO_MANY_REDIRECTS).
Prevent Regular Expression Denial of Service (ReDoS) in route matchers.
Avoid running expensive database or crypto operations inside the request interception pipeline.
Prerequisites & Background Knowledge
Why Interviewers Care
Frequent cause of critical site-wide production outages where all traffic drops to 0 or servers crash under 100% CPU utilization.
The Challenge
Diagnose an infinite redirect loop and a static asset interception flaw in Next.js Middleware. Write an optimized matcher configuration and safe redirect logic that prevents ERR_TOO_MANY_REDIRECTS.
Code Architecture & Implementation
1// BUGGY MIDDLEWARE: Causes ERR_TOO_MANY_REDIRECTS and 500s on static assets!2import { NextResponse } from 'next/server';3import type { NextRequest } from 'next/request';45export function middleware(request: NextRequest) {6 const token = request.cookies.get('token');78 // BUG 1: If user is unauthenticated, redirects to /login.9 // BUT /login also triggers this middleware!10 // At /login, token is missing -> Redirects to /login -> INFINITE LOOP!11 if (!token) {12 return NextResponse.redirect(new URL('/login', request.url));13 }14}1516// BUG 2: Matcher matches EVERYTHING, including /_next/static, images, and favicon!17// Every CSS and JS chunk triggers this middleware, quadrupling server latency!18export const config = {19 matcher: ['/:path*'],20};
Architectural Explanation
Because Middleware intercepts requests at the network edge, any bug affects 100% of website traffic. The most common outage is ERR_TOO_MANY_REDIRECTS: an unauthenticated user visits /dashboard, middleware redirects to /login, but /login has no token, so middleware redirects to /login again in an infinite loop. Always exclude the login route from redirection checks. Additionally, omitting negative lookaheads in the matcher runs middleware on every .js, .css, and image file, wasting server compute and adding latency to every asset.
Common Mistakes & Anti-Patterns
Redirecting to `/login` without checking if the current `pathname` is already `/login`.
Using `matcher: ["/:path*"]` without excluding `_next/static`, causing all CSS and JS chunks to execute middleware.
Writing complex regexes with catastrophic backtracking (`(a+)+$`) that crash Node.js CPU threads on malicious URLs (ReDoS).
Interview Follow-Up Traps
The interviewer asks: "Why do images in /public sometimes fail to load with middleware?" If your matcher does not exclude public file extensions (`.png`, `.svg`), middleware intercepts the static file and can inadvertently block or redirect it.
Frequently Asked Questions
Does proxy.ts in Next.js 16 use the same matcher syntax?
Yes! `proxy.ts` supports the identical `config.matcher` array syntax.
How many routes can you specify in the matcher array?
You can supply multiple regex strings or glob patterns in the array.
