nextjs
runtime_error
ai_generated
true
Error: Rewrite query parameters are lost after redirect in middleware
ID: nextjs/rewrite-query-params-lost
85%Fix Rate
85%Confidence
1Evidence
2024-03-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
Root Cause
When using NextResponse.rewrite() in middleware with a URL that includes query parameters, the parameters are stripped if the destination URL already has its own query string or if the rewrite target is a static path.
generic中文
在中间件中使用 NextResponse.rewrite() 时,如果目标 URL 已有自己的查询字符串或目标是静态路径,则查询参数会被剥离。
Official Documentation
https://nextjs.org/docs/app/api-reference/functions/next-response#rewriteWorkarounds
-
85% success Use NextResponse.next() with a modified URL that includes query parameters, then handle the rewrite in the page component using the searchParams prop.
Use NextResponse.next() with a modified URL that includes query parameters, then handle the rewrite in the page component using the searchParams prop.
-
75% success Store the query parameters in a cookie or header before rewriting, then read them in the page component.
Store the query parameters in a cookie or header before rewriting, then read them in the page component.
中文步骤
使用 NextResponse.next() 并修改 URL 包含查询参数,然后在页面组件中通过 searchParams 属性处理重写。
在重写前将查询参数存储在 cookie 或 header 中,然后在页面组件中读取。
Dead Ends
Common approaches that don't work:
-
70% fail
Next.js normalizes the URL and may strip duplicate or malformed query strings, especially if the destination path is a file-based route.
-
80% fail
Redirect changes the URL in the browser, which may break client-side state or cause infinite loops if the redirect target is the same page.
-
90% fail
The request object is immutable in middleware; modifying it directly has no effect on the rewrite.