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

使用NextJS和Next-Auth时,API路由中getServerSession()返回null

问题:Next-Auth API路由中getServerSession始终返回null

我是NextJS和Next-Auth的新手,尝试编写仅对已登录用户开放的安全API路由。我能在客户端通过useSession()成功获取会话,但在API路由中实现逻辑时,getServerSession()始终返回null。我已经复制了文档中的最简示例,请问我遗漏了什么?


路由代码(src/pages/api/users/getUser.ts)

import { getServerSession } from 'next-auth/next'
import { authOptions } from '../auth/[...nextauth]'
import { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const session = await getServerSession(req, res, authOptions)
  console.log('session', session)

  if (session) {
    res.send({ content: 'SUCCESS' })
  } else {
    res.send({ error: 'ERROR' })
  }
}

NextAuth配置(src/pages/api/auth/[...nextauth].ts)

import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
import { PrismaAdapter } from '@next-auth/prisma-adapter'
import prisma from '../../../../prisma/db/prismadb'

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID || '',
      clientSecret: process.env.GITHUB_SECRET || '',
    }),
  ],
  pages: {
    signIn: '/',
    signOut: '/',
  },
}

export default NextAuth(authOptions)

依赖项

"dependencies": {
    "@next-auth/prisma-adapter": "^1.0.5",
    "@next/font": "13.1.6",
    "@prisma/client": "^4.10.1",
    "@types/node": "18.11.19",
    "@types/react": "18.0.27",
    "@types/react-dom": "18.0.10",
    "axios": "^1.3.2",
    "dotenv-cli": "^7.0.0",
    "eslint": "8.33.0",
    "eslint-config-next": "13.1.6",
    "next": "13.1.6",
    "next-auth": "^4.19.2",
    "prisma": "^4.9.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "styled-components": "^5.3.6",
    "typescript": "4.9.5"
  },
  "devDependencies": {
    "@types/styled-components": "^5.1.26"
  }

解决方案

以下是几个常见的排查方向和修复步骤:

1. 配置NEXTAUTH_SECRET环境变量

NextAuth依赖该密钥加密会话数据,缺失会导致服务器端无法解析会话。在.env文件中添加:

NEXTAUTH_SECRET=your-random-secret-key

可通过openssl rand -hex 32命令生成安全的随机密钥。

2. 确保API请求携带会话Cookie

客户端调用API时,需自动携带NextAuth的会话Cookie:

  • 若使用axios,需配置withCredentials: true:
    axios.get('/api/users/getUser', { withCredentials: true })
    
  • 浏览器直接访问API时,检查是否存在next-auth.session-token或__Secure-next-auth.session-token Cookie。

3. 验证authOptions的导入路径

确认getUser.ts中authOptions的导入路径正确,若目录层级有变动,可尝试绝对路径导入:

import { authOptions } from '../../auth/[...nextauth]'

4. 检查版本兼容性

你的Next.js(13.1.6)和Next-Auth(4.19.2)版本兼容,但可尝试更新到最新稳定版修复潜在bug:

npm update next-auth

5. 确认Prisma Adapter配置正常

检查Prisma数据库连接是否正常,运行prisma migrate dev确保NextAuth所需的User、Session等表已生成。

6. 调试会话解析过程

在getServerSession调用前打印请求Cookie,确认会话Cookie是否存在:

console.log('req.cookies', req.cookies)

若Cookie存在但getServerSession仍返回null,大概率是NEXTAUTH_SECRET不匹配导致签名验证失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:06:25