Next.js中间件匹配页面时客户端getServerSideProps props为undefined问题
解决Next.js中间件导致getServerSideProps props客户端undefined的问题
问题原因
当middleware的matcher匹配到页面时,直接返回NextResponse.next()未携带请求上下文,导致服务器端getServerSideProps生成的props无法正确传递到客户端(虽然getServerSideProps已执行,但客户端接收不到)。
解决方案
修改middleware中的NextResponse.next()调用,传入{ request: req }参数保留请求上下文,同时优化matcher的正则写法以符合Next.js规范:
import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export default async function middleware(req: NextRequest) { // 传递原始请求上下文,确保props正常传递到客户端 return NextResponse.next({ request: req }); } export const config = { // 使用Next.js官方推荐的动态路径匹配写法,更精准 matcher: ['/(tag|about)/:path*'], };
额外检查点
确认页面组件正确接收props,示例如下:
export default function TagPage({ content }) { // 确保组件正确接收并使用props return <div>{content}</div>; } export async function getServerSideProps() { return { props: { content: '标签页内容' }, }; }
内容的提问来源于stack exchange,提问作者kennsorr
相关产品推荐
相关产品推荐

