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

Next.js(TypeScript)报错:GetServerSideProps无'req'/'res'属性

解决Next-auth getServerSideProps中context.req/res类型报错问题

你的报错根源在于context参数的类型声明错误:你把GetServerSideProps(这是整个服务器端props函数的类型)当成了context对象的类型,而context实际的类型应该是GetServerSidePropsContext。

修正步骤:

  1. 从Next.js中导入GetServerSidePropsContext类型
  2. 将getServerSideProps的context参数类型替换为GetServerSidePropsContext

修正后的完整代码:

import React from "react";
import type { GetServerSideProps, GetServerSidePropsContext } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../../pages/api/auth/[...nextauth]";

function EditProfile() {
  return (
    <>
      ....
    </>
  );
}

export async function getServerSideProps(context: GetServerSidePropsContext) {
  const session = await getServerSession(context.req, context.res, authOptions);

  return {
    props: { session }, // 建议把session传入组件props供使用
  };
}

export default EditProfile;

另一种更规范的写法(指定整个函数的类型):

你也可以不单独声明context的类型,直接给getServerSideProps函数指定GetServerSideProps类型,TypeScript会自动推断context的正确类型:

export const getServerSideProps: GetServerSideProps = async (context) => {
  const session = await getServerSession(context.req, context.res, authOptions);

  return {
    props: { session },
  };
};

以上两种写法都能彻底解决req/res属性不存在的类型报错问题。

内容的提问来源于stack exchange,提问作者Tsabary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:20:43