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

Next JS 14中getServerSession获取会话返回null求助

Next.js 14 + NextAuth Credentials认证:API路由getServerSession返回null但客户端正常

问题描述

使用Next.js 14搭配NextAuth的Credentials认证方式,客户端可正常获取会话信息,但在App Router的API路由中调用getServerSession时始终返回null,导致接口返回401未授权。相关API路由代码如下:

import { NextRequest, NextResponse } from "next/server";
import supabase from "@/app/backend/db/supabase";
import { getServerSession } from "next-auth/next";
import authOptions from "@/app/backend/lib/authentication/authOptions";

export async function GET(
  req: NextRequest,
  { params }: { params: { slug: string[] } }
) {
  const session = await getServerSession(authOptions);
  console.log("aaaaa", session);
  if (session?.user) {
    try {
      const { slug } = params;
      console.log(slug);
      let { data, error } = await supabase
        .from(slug[0])
        .select("*")
        .eq(slug[1], slug[2]);

      if (error) {
        console.log(error);
        return NextResponse.json({ error: error.message }, { status: 500 });
      }

      return NextResponse.json({ success: true, data }, { status: 200 });
    } catch (error) {
      console.log(error);
      return NextResponse.json(
        { error: "Internal Server Error" },
        { status: 500 }
      );
    }
  } else {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
}

排查步骤

1. 检查authOptions核心配置

  • 必须配置session: { strategy: "jwt" }:Credentials认证不支持数据库会话存储,只能用JWT策略
  • 确保authOptions.secret与.env中的NEXTAUTH_SECRET完全一致,这是JWT签名验证的关键
  • 确认providers数组中包含正确配置的Credentials provider,且authorize函数能正常返回用户信息

2. 验证请求是否携带会话Cookie

  • 在浏览器Network面板查看API请求的Cookie头,确认存在next-auth.session-token或__Secure-next-auth.session-token
  • 若为跨域请求,需在authOptions中添加cors配置,或确保客户端请求时设置了credentials: true

3. 适配App Router的getServerSession调用

  • 确认app/api/auth/[...nextauth]/route.ts文件存在,且正确导出NextAuth handler:
    import NextAuth from "next-auth"
    import authOptions from "@/app/backend/lib/authentication/authOptions"
    
    const handler = NextAuth(authOptions)
    export { handler as GET, handler as POST }
    
  • 尝试手动解析JWT验证会话,排查getServerSession是否存在配置问题:
    import { jwtVerify } from "next-auth/jwt"
    
    const sessionToken = req.cookies.get("next-auth.session-token")?.value
    if (sessionToken) {
      const decoded = await jwtVerify(sessionToken, process.env.NEXTAUTH_SECRET!)
      console.log("Decoded JWT:", decoded)
    }
    
    若能解析出用户信息,说明getServerSession的配置存在问题;若解析失败,说明Cookie无效或签名错误

4. 环境变量检查

  • 生产环境必须手动设置NEXTAUTH_SECRET,开发环境建议统一设置避免不一致
  • 确认NEXTAUTH_URL配置正确,生产环境需设置为实际域名(如https://yourdomain.com),开发环境为http://localhost:3000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:54:49