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

Next Auth集成报错:options.providers不可迭代问题求助

问题原因

你在getEmployeeData.js中导入的authOptions是[...nextauth].js默认导出的NextAuth处理函数,而非配置对象。unstable_getServerSession需要接收的是NextAuth的原始配置对象,而不是经过NextAuth()包装后的处理函数,这就导致内部无法识别providers数组,抛出TypeError: options.providers is not iterable错误。

错误重复三次大概率是开发环境下请求重试或热重载触发了多次请求。

解决方案

1. 修改[...nextauth].js,单独导出配置对象

将配置对象抽离出来并命名导出,同时用该配置创建NextAuth处理函数作为默认导出:

import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import clientPromise from '../../../lib/mongodb'
import { compare } from 'bcryptjs'

// 单独定义并导出配置对象
export const authOptions = {
    session: {
        strategy: "jwt"
    },
    providers: [
        CredentialsProvider({
            name: "Email and Password",
            credentials: {
                email: { label: "Email", type: "email", placeholder: "Email Address" },
                password: { label: "Password", type: "password", placeholder: "Password" }
            },
            async authorize(credentials, req) {
                const db = (await clientPromise).db();
                const employees = db.collection('employees');
                const res = await employees.findOne({
                    email: credentials.email
                });
                if (!res) {
                    throw new Error('No user found with those details');
                }
                const checkPassword = await compare(credentials.password, res.password);
                if (!checkPassword) {
                    throw new Error('Incorrect username or password');
                }
                return res;
            }
        }),
    ],
    pages: {
        signIn: "/signin"
    }
}

export default NextAuth(authOptions);

2. 修改getEmployeeData.js,导入正确的配置对象

把默认导入改为命名导入,获取刚才导出的authOptions:

import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "../auth/[...nextauth]" // 改为命名导入
import clientPromise from "../../../lib/mongodb";

export default async function getEmployeeData(req, res) {
    const session = await unstable_getServerSession(req, res, authOptions);
    if (session) {
        res.status(200).json({ success: "You got it!" });
    } else {
        // 添加未授权的响应处理,避免请求挂起
        res.status(401).json({ error: "Unauthorized" });
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:42:50