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

如何在Next.js的getServerSideProps中获取Auth0 User对象并解决TS报错

问题解决方法

你遇到的TypeScript报错是因为新版@auth0/nextjs-auth0 SDK的withPageAuthRequired方法,包装组件和包装getServerSideProps的调用规则不同,你混淆了两种场景的传参格式。

修正后完整代码

import { withPageAuthRequired, GetServerSidePropsContextWithSession } from '@auth0/nextjs-auth0';

// 定义组件props类型
type ProfileProps = {
  user: {
    name: string;
    // 可根据实际业务补充其他user字段
  };
  newData: string;
};

// 组件部分保持正常包装即可
export default withPageAuthRequired(function Profile({ user, newData }: ProfileProps) {
  return (
    <>
      <div>{user.name}</div>
    </>
  );
});

// getServerSideProps部分直接传异步函数,不需要外层套对象
export const getServerSideProps = withPageAuthRequired(
  async (context: GetServerSidePropsContextWithSession) => {
    // 可直接从context中获取user对象使用
    const { user } = context;
    console.log('当前登录用户信息:', user);

    return {
      props: {
        newData: "user"
      }
    };
  }
);

改动说明

  • 旧版SDK包装getServerSideProps需要传入带getServerSideProps字段的对象,2.x及以上版本已经废弃该写法,直接传入异步函数即可
  • 可以直接从GetServerSidePropsContextWithSession类型的context参数中解构出已登录的user对象,不需要额外拉取用户信息
  • 补充对应TS类型定义即可消除类型报错
  • 如果修改后还是报错,先升级@auth0/nextjs-auth0到最新正式版即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:15:03