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

Next.js 13中NextAuth调用getServerSession出现TypeError错误求助

问题:Next.js 13中调用getServerSession触发TypeError: res.getHeader is not a function错误

基于Next.js 13开发项目,使用NextAuth实现身份验证时,在API路由中调用getServerSession(req, res, authOptions)校验用户登录状态,触发了TypeError: res.getHeader is not a function错误。

相关代码

users/routes.ts

import { NextRequest, NextResponse } from 'next/server'
import { connectMongoDB } from "@/lib/mongodb";
import User from "@/models/user"
import { getServerSession } from 'next-auth';
import { authOptions } from '../auth/[...nextauth]/route';
export async function GET(req: NextRequest, res: NextResponse) {

  const session = await getServerSession(req, res, authOptions)
  if (!session) {
    return NextResponse.json({ message: "You must be logged in.", status: 401 });

  }
  try {
    await connectMongoDB();
    const users = await User.find();
    return NextResponse.json({ message: "", status: 200, data: users })
  } catch (error) {
    return NextResponse.json({ message: "Error occured..", status: 500 })
  }
}

auth/[...nextauth]/routes.js

import { connectMongoDB } from "@/lib/mongodb";
import User from "@/models/user";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Email and password",
      credentials: {},
      async authorize(credentials, req) {
        const { email, password } = credentials;
        try {
          await connectMongoDB();
          const user = await User.findOne({ email })

          if (!user) {
            return null;
          }
          const passwordMatch = await bcrypt.compare(password, user.password)
          if (!passwordMatch) {
            return null;
          }
          return user;
        } catch (error) {
          console.log('error', error)
          return null;
        }
      },
    }),
  ],
  session: {
    strategy: "jwt",
  },
  secret: process.env.NEXTAUTH_SECRET,
  pages: {
    signIn: "/",
  },
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

错误原因

Next.js 13的App Router路由(app目录下的route.ts/js)使用的是NextRequest和NextResponse对象,而getServerSession的前两个参数req、res是针对Pages Router(pages/api下的路由)设计的Node.js原生HTTP请求/响应对象,两者不兼容,因此传入App Router的NextResponse会触发res.getHeader is not a function错误。

解决方案

正确实现方式:仅传入authOptions

在App Router环境下,getServerSession会自动从当前请求上下文获取所需的请求头、Cookie等信息,无需手动传入req和res,直接传入authOptions即可,这是官方推荐的用法。

修改后的users/routes.ts代码:

import { NextRequest, NextResponse } from 'next/server'
import { connectMongoDB } from "@/lib/mongodb";
import User from "@/models/user"
import { getServerSession } from 'next-auth';
import { authOptions } from '../auth/[...nextauth]/route';

export async function GET(req: NextRequest) {
  // 仅传入authOptions
  const session = await getServerSession(authOptions);
  
  if (!session) {
    return NextResponse.json({ message: "You must be logged in.", status: 401 });
  }
  
  try {
    await connectMongoDB();
    const users = await User.find();
    return NextResponse.json({ message: "", status: 200, data: users })
  } catch (error) {
    return NextResponse.json({ message: "Error occured..", status: 500 })
  }
}

补充说明

你之前尝试的getServerSession(authOptions)是完全正确的实现方式,符合NextAuth在Next.js 13 App Router中的用法规范,无需担心正确性。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:40:33