nextjs runtime_error ai_generated true

错误:中间件重写后查询参数丢失

Error: Rewrite query parameters are lost after redirect in middleware

ID: nextjs/rewrite-query-params-lost

其他格式: JSON · Markdown 中文 · English
85%修复率
85%置信度
1证据数
2024-03-15首次发现

版本兼容性

版本状态引入弃用备注
[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.

generic

官方文档

https://nextjs.org/docs/app/api-reference/functions/next-response#rewrite

解决方案

  1. 使用 NextResponse.next() 并修改 URL 包含查询参数,然后在页面组件中通过 searchParams 属性处理重写。
  2. 在重写前将查询参数存储在 cookie 或 header 中,然后在页面组件中读取。

无效尝试

常见但无效的做法:

  1. 70% 失败

    Next.js normalizes the URL and may strip duplicate or malformed query strings, especially if the destination path is a file-based route.

  2. 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.

  3. 90% 失败

    The request object is immutable in middleware; modifying it directly has no effect on the rewrite.