You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 13:12:05