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

Next.js/NextAuth疑难:API路由无法获取Session返回401

NextAuth受保护API路由Session为null返回401排查方案

1. 检查authOptions导入路径正确性

你的API路由中导入authOptions的路径为'pages/api/auth/[...nextauth]',但从你的[...nextauth].ts文件路径src/pages/api/auth/[...nextauth].ts来看,若项目使用src目录作为根目录,正确的相对路径应为'../auth/[...nextauth]'(假设API路由在src/pages/api/board/[boardId].ts)。错误的导入路径会导致unstable_getServerSession无法获取正确的认证配置,进而无法解析Session。

2. 修复服务端API请求的Cookie传递问题

在getServerSideProps中调用handleFetchData时,请求是在服务端发起的,不会自动携带浏览器的Cookie,需要手动传递Cookie头给axios:

const handleFetchData = async ({boardId, req}) => {
  const baseUrl = getBaseUrl(req)
  const axiosConfig = {}
  if (req) {
    // 服务端请求时,手动传递Cookie头
    axiosConfig.headers = {
      Cookie: req.headers.cookie
    }
  } else {
    // 客户端请求时开启凭证传递
    axiosConfig.withCredentials = true
  }
  return axios.get(`${baseUrl}/api/board/${boardId}`, axiosConfig)
    .then(({data}) => data)
    .catch(err => { console.log(err)})
}

这是导致服务端渲染时API路由返回401的核心原因之一——服务端发起的请求没有携带认证Cookie,自然无法获取Session。

3. 显式配置Session策略

使用PrismaAdapter时,建议显式声明Session策略为database(NextAuth默认会适配,但显式配置可避免潜在的自动适配问题):
在[...nextauth].ts的authOptions中添加:

session: {
  strategy: "database",
},

4. 检查getToken的导入与使用

你的API路由中使用了getToken({ req })但未显示导入相关模块,需补充导入:

import { getToken } from "next-auth/jwt"

缺失导入会导致运行时错误,可能中断Session验证逻辑。

5. 替换不稳定的Session获取API

若你使用的NextAuth版本≥v4.20.0,unstable_getServerSession已被稳定版getServerSession替代,建议替换以避免API不稳定带来的问题:

// 导入替换
import { getServerSession } from "next-auth/next"

// 使用替换
const session = await getServerSession(req, res, authOptions)

6. 验证Cookie的一致性

  • 检查Chrome开发者工具中Cookie的domain、path、sameSite属性,确保API请求的URL与Cookie的匹配规则一致。
  • 确认getBaseUrl函数在客户端和服务端返回的域名完全一致(例如均为http://localhost:3000),不一致的域名会导致Cookie无法传递。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:01:07