AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Memory Leak In Next.Js Dev Server When Route Handler Runs Async Loop

Next.js dev server leaks memory when a route handler executes an infinite async loop, eventually crashing the process. Production build and plain Node.js do not exhibit this issue.

highConfidence 75%Next.jsAffected V16.0.1Affected V16.0.2-Canary.3

Origin Analysis

Next.js dev server wraps route handlers with AsyncLocalStorage to track request context, and each await creates a new asynchronous resource that is not released until the request completes. Since the request never completes due to an infinite loop, these resources accumulate, causing heap growth and eventual crash. This indicates a design flaw in the dev server's async context management.
1. Create a Next.js app with a route handler at /app/test/route.ts containing the provided code with an infinite await loop. 2. Run `npm run dev`. 3. Open http://localhost:3000/test. 4. Observe increasing heap usage in GC logs and eventual server crash.

Fixing Code Block

Edge Case Audit

This Hotfix is a temporary workaround and not a permanent fix for the Next.js dev server's async context handling. It may alter timing behavior and should be removed once the underlying issue is resolved. Rolling back is straightforward by restoring the original loop, but the memory leak will return. For production, no changes are needed since the issue does not occur there.

Ecosystem Topology