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

Middleware Set-Cookie On Prerendered Static Pages Allows CDN Caching Of Auth Tokens

When middleware adds Set-Cookie headers to a response for a prerendered static page, Next.js preserves the page's original Cache-Control: s-maxage=31536000. Shared CDNs that obey s-maxage may cache and serve the response including sensitive Set-Cookie headers to other users, causing cross-user authentication token leakage.

criticalConfidence 95%Next.jsAffected V15.5.9Affected V16.2.12

Origin Analysis

Next.js middleware runs before the final response is generated. When middleware takes NextResponse.next() and sets cookies via response.cookies.set() or directly setting the set-cookie header, the framework does not override the Cache-Control header from the underlying statically generated page. The statically generated page has Cache-Control: s-maxage=31536000, making it eligible for shared cache storage. Because RFC 6265 Section 7.3 states shared caches must not store or distribute responses containing Set-Cookie unless the response explicitly allows it, but the presence of s-maxage explicitly permits caching, CDNs may cache the entire response including the Set-Cookie headers. Next.js itself does not automatically adjust cache headers when middleware adds Set-Cookie, leading to the unsafe response.
1. Clone https://github.com/uiYzzi/nextjs-middleware-setcookie-cache-leak 2. npm install && npm run build && npm start 3. Run curl -sI -b "rt=USER_A" http://localhost:3000/ 4. Observe the response contains Set-Cookie headers and Cache-Control: s-maxage=31536000 simultaneously.

Fixing Code Block

Edge Case Audit

Applying no-store globally to all middleware responses may degrade performance for pages that do not require personalization. To avoid unnecessary performance impact, conditionally set the header only when cookies are actually added (as shown in the fix). Also be aware that no-store will prevent both shared and private caches from storing the response, which may increase server load. If you later upgrade to a Next.js version that fixes the underlying issue automatically, remove this manual override to restore normal caching behavior. Rollback by deleting the Cache-Control override line and redeploying.

Ecosystem Topology