URL search parameters including spaces are duplicated after middleware rewrite #79375
Labels
linear: next
Confirmed issue that is tracked by the Next.js team.
Middleware
Related to Next.js Middleware.
Uh oh!
There was an error while loading. Please reload this page.
Link to the code that reproduces this issue
https://github.com/federicobadini/search-param-bug-repro
To Reproduce
When using Next.js middleware to perform a rewrite, URL search parameters containing spaces (encoded as +) result in duplicated query parameters—one with the expected value, and one with an empty string.
To replicate the bug simply:
Trigger buggy behaviour
buttonTrigger fixed behaviour
If you prefer, the minimal repro is already deployed on Vercel here: https://search-param-bug-repro.vercel.app/
Current vs. Expected behavior
When a request with a query string containing + (e.g., ?q=hello+world) hits a middleware that rewrites the path, the resulting request seems to reach the page with two parameters instead of just one:
q=hello world ✅ (decoded correctly)
q="" ❌ (duplicate with empty value)
Provide environment information
Which area(s) are affected? (Select all that apply)
Middleware
Which stage(s) are affected? (Select all that apply)
Vercel (Deployed)
Additional context
The suggested workaround - manually re-encoding the search parameters using encodeURIComponent() before the middleware rewrite - was discovered after extensive debugging. This approach appears to prevent the issue entirely.
It seems likely that Next.js performs some internal handling of the query string during the rewrite process, and may be misinterpreting + at some stage, resulting in duplicated parameters.
The minimal reproduction highlights this clearly. When request.nextUrl is passed directly to rewrite(), the bug occurs. However, if the URL is reconstructed manually with properly encoded parameters, everything works as expected.
The text was updated successfully, but these errors were encountered: