nextjs config_error ai_generated true

错误:中间件重定向到了包含查询字符串的 URL。重定向必须仅指向路径名。

Error: Middleware redirected to a URL with a query string. Redirects must be to pathnames only.

ID: nextjs/middleware-redirect-to-internal-with-query

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

版本兼容性

版本状态引入弃用备注
Next.js 13.x active
Next.js 14.x active
Next.js 15.x active

根因分析

在 Next.js 中间件中,`redirect` 方法(来自 NextResponse)期望一个不带查询参数的路径名字符串。传递带有查询字符串的 URL 会导致内部错误。

English

In Next.js middleware, the `redirect` method (from NextResponse) expects a pathname string without query parameters. Passing a URL with a query string causes an internal error.

generic

官方文档

https://nextjs.org/docs/app/building-your-application/routing/middleware#redirecting

解决方案

  1. Redirect to a pathname without query strings, then handle query parameters client-side using useSearchParams or server-side in the target page.
  2. Use NextResponse.redirect with a path and then append query parameters via a server-side rewrite or client-side navigation.

无效尝试

常见但无效的做法:

  1. 80% 失败

    The redirect function does not support query strings; it strips them or throws an error.

  2. 50% 失败

    NextResponse.redirect internally validates the URL; setting headers directly bypasses this but may cause hydration or caching issues.

  3. 60% 失败

    Rewrite changes the URL server-side but does not cause a client-side redirect, which may not achieve the desired navigation.