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

NextAuth.js中getServerSession API调用返回null触发401错误

解决NextAuth.js中服务器端API调用无法获取会话的问题

问题核心:你在getServerSideProps里能正常拿到会话,但用Axios调用内部API时,API里的getServerSession返回null触发401,本质是服务器端发起的Axios请求不会自动携带用户的会话Cookie——浏览器直接请求时会自动带上Cookie,所以API校验能通过,但服务器端的Axios请求是独立的,默认没带Cookie,导致API无法识别会话。

下面给两种可行解决方案:

方案一:直接在getServerSideProps中处理数据库逻辑(推荐)

既然已经在getServerSideProps里拿到了会话,直接在这里连接数据库查询用户数据,跳过额外的API调用,既高效又避免Cookie问题。

修改后的前端代码:

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

  if (session) {
    try {
      // 直接连接数据库查询用户,无需调用API
      await connectToDB();
      const user = await User.findById(session.user.uid);
      
      if (!user) {
        throw new Error("No user found for the given id.");
      }

      return {
        props: {
          user: user,
        },
      };
    } catch (error) {
      // 根据需求处理错误,比如重定向或返回错误状态
    }
  }

  return {
    redirect: {
      destination: "/api/auth/signin",
      permanent: false,
    },
  };
}

方案二:给Axios请求手动携带会话Cookie

如果必须通过API获取数据,需要从当前请求中提取Cookie,手动添加到Axios的请求头里,让API能识别会话。

修改后的前端代码:

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

  if (session) {
    try {
      // 从当前请求的headers中获取Cookie,传给Axios
      const { data } = await Axios.get(`/api/profile/${session.user.uid}`, {
        headers: {
          Cookie: context.req.headers.cookie || "",
        },
      });
      return {
        props: {
          user: data,
        },
      };
    } catch (error) {}
  }

  return {
    redirect: {
      destination: "/api/auth/signin",
      permanent: false,
    },
  };
}

补充说明

  • 方案一性能更优,减少了一次服务器内部请求,是Next.js中处理这类场景的常规做法。
  • 方案二中仅服务器端发起的请求需要手动传Cookie,客户端的Axios请求只要配置withCredentials: true就会自动携带Cookie。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:37:24