Next.js App Router中useSearchParams无法获取中间件设置的查询参数
Next.js App Router 中间件设置查询参数后,客户端useSearchParams获取不到的问题
我正在使用带有App Router的Next.js,在middleware.ts中设置了查询参数,但在客户端组件中使用useSearchParams() Hook时,仅返回ReadonlyURLSearchParams {size: 0}。请问问题出在哪里?
以下是我的中间件代码:
export async function middleware(request: NextRequest) { const pathname = request.nextUrl.pathname; console.log("pathansdjdsk:", pathname); const isFreelancerDashboard = pathname.startsWith("/freelancer-dashboard"); const isChatWindow = pathname.startsWith("/chat"); const isAuth = await isLoggedIn(); console.log("Inside Middleware!!----------------"); if (!isAuth) { console.log("Not Authenticated!!!!!"); return NextResponse.redirect(new URL("/", request.url)); } const payload = await getPayload(); if (isChatWindow) { console.log("Inside chat window"); request.nextUrl.searchParams.set("userId", payload.ctx.userId); console.log("use search params ", payload.ctx.userId); } // Continue processing if no condition is met return NextResponse.next(); } export const config = { matcher: ["/freelancer-dashboard/:path*", "/chat/:path*"], };
我已尝试查找设置查询参数的方法,但没有成功。
更新:
尝试建议的方案后,nextURL更新如下,但URL查询参数仍为空:
{ href: 'http://localhost:3000/chat/2-1-1?userId=2', origin: 'http://localhost:3000', protocol: 'http:', username: '', password: '', host: 'localhost:3000', hostname: 'localhost', port: '3000', pathname: '/chat/2-1-1', search: '?userId=2', searchParams: URLSearchParams { }, hash: '' }
在组件中打印window.location.href时,得到以下URL。我访问的是动态路由src\app\chat[id]\page.tsx:
hash : "" host : "localhost:3000" hostname : "localhost" href : "http://localhost:3000/chat/2-1-1" origin : "http://localhost:3000" password : "" pathname : "/chat/2-1-1" port : "3000" protocol : "http:" search : "" searchParams: URLSearchParams {size: 0}
问题原因
你当前仅修改了request.nextUrl对象,但NextResponse.next()默认不会将修改后的URL同步到客户端的地址栏和路由上下文里,所以客户端无法通过useSearchParams获取到设置的参数。
解决方法
方法1:重定向到带查询参数的URL(地址栏可见参数)
如果允许查询参数显示在地址栏,可以通过重定向将修改后的URL传递给客户端:
if (isChatWindow) { console.log("Inside chat window"); request.nextUrl.searchParams.set("userId", payload.ctx.userId); console.log("use search params ", payload.ctx.userId); // 重定向到更新后的URL return NextResponse.redirect(request.nextUrl); }
方法2:通过响应头传递数据(地址栏无参数)
如果不想暴露查询参数,可以将数据放在响应头中,客户端通过头信息获取:
// 中间件中设置响应头 if (isChatWindow) { const response = NextResponse.next(); response.headers.set("x-user-id", payload.ctx.userId); return response; }
客户端组件中获取:
import { useHeaders } from 'next/headers'; export default function ChatPage() { const headers = useHeaders(); const userId = headers.get('x-user-id'); // 使用userId进行后续逻辑处理 }
如果是服务器组件,直接用headers()函数获取即可,无需客户端Hook。
内容的提问来源于stack exchange,提问作者MAYANK CHHIPA
相关产品推荐
相关产品推荐

