错误:中间件重写后查询参数丢失
Error: Rewrite query parameters are lost after redirect in middleware
ID: nextjs/rewrite-query-params-lost
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
根因分析
在中间件中使用 NextResponse.rewrite() 时,如果目标 URL 已有自己的查询字符串或目标是静态路径,则查询参数会被剥离。
English
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.
官方文档
https://nextjs.org/docs/app/api-reference/functions/next-response#rewrite解决方案
-
使用 NextResponse.next() 并修改 URL 包含查询参数,然后在页面组件中通过 searchParams 属性处理重写。
-
在重写前将查询参数存储在 cookie 或 header 中,然后在页面组件中读取。
无效尝试
常见但无效的做法:
-
70% 失败
Next.js normalizes the URL and may strip duplicate or malformed query strings, especially if the destination path is a file-based route.
-
80% 失败
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% 失败
The request object is immutable in middleware; modifying it directly has no effect on the rewrite.