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

NextAuth.js中getSession在API接口GET正常POST请求失败问题

摘要:
  • 已找到临时解决方法,可查看回答区域
  • 本问题仍待解答,若有能解释问题成因及提供正规解决方案的回答,我会采纳
问题详情:

我有一个受NextAuth.js 4.24.4保护的API接口,之前可正常运行,但突然失效,无法定位变更点。

GET请求可成功执行,但POST请求失败,报错如下:

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://localhost:3300/api/auth/session',
  message: undefined
}

相关错误提示要求确认配置正确,但配置未发生变更,理论上应仍可正常运行。

我添加了一个调试Provider,但问题仍未解决:

CredentialsProvider({
      name: 'Credentials',
      credentials: {
        username: { label: "Username", type: "text" },
        password: {  label: "Password", type: "password" }
      },
      authorize: async (credentials) => {
        if (credentials.username === 'debug' && credentials.password === 'debug') {
          return { id: 1, name: 'Debug User', email: 'debug@example.com' }
        }
        return false
      }
    }),
API接口代码

受保护的处理器代码与官方教程大致一致:

export default async function protectedHandler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  console.log('The request to get Session', {cookies: req.cookies,  headers: req.rawHeaders})
  const session = await getSession({ req });
  try {
    var { user } = session;
    console.log('Successfully retrieved Session', {req})
  } catch (e) {
    res.status(401).json({ error: 'failed to authenticate user' });
  }

  if (session) {
    const result = await startExecution(req, res, user);
    return res.send({
      content: result,
    });
  }
  console.log('Not Successfully retrieved Session', {req})
  res.status(401).json({ error: 'failed to authenticate' });
}
日志信息

GET请求运行正常,但POST请求失败。

Cookie与请求头

GET与POST请求中的内容一致:

cookies: {
    'next-auth.csrf-token': 'SOMETOKEN',
    'next-auth.callback-url': 'http://localhost:3300/',
    'next-auth.session-token': 'SOMESESSIONTOKEN'
  },
  headers: [
    'Host',
    'localhost:3300',
    'User-Agent',
    'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0',
    'Accept',
    '*/*',
    'Accept-Language',
    'en-US,en;q=0.5',
    'Accept-Encoding',
    'gzip, deflate, br',
    'Referer',
    'http://localhost:3300/foo',
    'Connection',
    'keep-alive',
    'Cookie',
    'next-auth.csrf-token=<SOMETOKEN>; next-auth.callback-url=http%3A%2F%2Flocalhost%3A3300%2F; next-auth.session-token=<SOMESESSIONTOKEN>',
    'Sec-Fetch-Dest',
    'empty',
    'Sec-Fetch-Mode',
    'cors',
    'Sec-Fetch-Site',

请求日志差异

仅GET请求包含:

headers:
    'If-None-Match',
    '"vy6cdinx812znr"'

仅POST请求包含:

'Content-Type',
    'text/plain;charset=UTF-8',
    'Content-Length',
    '860',
    'Origin',
    'http://localhost:3300',

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:38:09