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

如何从异步函数返回next-auth的authOptions配置?

解决NextAuth异步加载AWS Secrets Manager配置的问题

你的代码报错是因为buildAuthOptions()是异步函数,返回的是Promise对象,而非直接的NextAuthOptions配置。NextAuth初始化时拿到的是Promise,自然无法读取providers属性,导致"options.providers is not iterable"错误。

最佳实践

将异步获取配置的逻辑放到请求处理函数内部,先等待配置加载完成,再传递给NextAuth初始化。同时可以加入缓存优化,避免重复调用AWS接口。

修正后的完整代码

import NextAuth from "next-auth";
import CognitoProvider from "next-auth/providers/cognito";
import type { NextApiRequest, NextApiResponse } from "next";
import type { NextAuthOptions } from "next-auth";

type AuthSecrets = {
  cognitoClientId: string;
  cognitoClientSecret: string;
  cognitoDomain: string;
  JWTSecret: string;
};

const getSecret = async (secretName: string): Promise<AuthSecrets> => {
  // 你的AWS Secrets Manager获取逻辑
};

let cachedSecrets: AuthSecrets | null = null;

export const buildAuthOptions = async (): Promise<NextAuthOptions> => {
  // 缓存secrets,避免重复调用AWS接口
  if (!cachedSecrets) {
    cachedSecrets = await getSecret("secret_name");
  }

  return {
    providers: [
      CognitoProvider({
        clientId: cachedSecrets.cognitoClientId,
        clientSecret: cachedSecrets.cognitoClientSecret,
        issuer: cachedSecrets.cognitoDomain,
      }),
    ],
    secret: cachedSecrets.JWTSecret,
  };
};

// 异步处理请求,先获取配置再初始化NextAuth
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const authOptions = await buildAuthOptions();
  return NextAuth(req, res, authOptions);
};

export { handler as GET, handler as POST };

补充说明

  • 缓存逻辑可减少AWS API调用次数,降低成本并提升性能;若不需要缓存,直接移除cachedSecrets相关代码即可。
  • 确保getSecret函数返回的对象类型与AuthSecrets完全匹配,避免类型不兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 08:17:20