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

Middleware Rewrite Internal Request URL Re-Serializes Incorrectly Causing Query Param Value With & To Split

When a middleware rewrites a request and sets a query parameter whose value contains a literal '&', the internal request generated by Next.js re-serializes the URL using URLSearchParams.toString(), which decodes and re-encodes the value, causing the '&' to be treated as a query string separator. This results in the value being truncated and the secret parameter leaking to the top-level, breaking the rewrite flow.

highConfidence 90%Next.jsHydrationnext buildServer ActionsAffected V16.1.6

Origin Analysis

Next.js internal request generation for rewrites reconstructs the URL's query string from parsed URLSearchParams instead of preserving the original encoded search string. The URLSearchParams.toString() method encodes '&' within values as '%26', but when the URL is later decoded and re-serialized, the '%26' is converted back to '&' and then treated as a delimiter, splitting the value into separate top-level parameters.
1. Create a Next.js application with middleware that rewrites /_next/image and injects a secret query param into the image URL passed as the `url` parameter. 2. Ensure the image URL already contains a query string (e.g., a cache-busting key). 3. In middleware, set `imageUrl.searchParams.set('secret', secret)` and then `rewriteUrl.searchParams.set('url', imageUrl.toString())`. 4. Make a request to /_next/image with initial parameters; the first rewrite serializes correctly. 5. The internal request triggered by the rewrite hits the middleware again, but now the `url` parameter value is cut at the first '&' and the secret appears as a top-level parameter, causing the sanity check to throw.

Fixing Code Block

Edge Case Audit

Removing the `url.search` assignment may affect any code that relies on the side effect of normalizing the query string (e.g., sorting parameters or removing empty values). Test thoroughly with middleware that modifies query parameters directly. If issues arise, rollback by restoring the line and consider a more targeted fix that only preserves encoding for values containing '&'.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state