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

Next.js API路由认证报错:TypeError: Cannot read properties of undefined (reading 'secret')

问题解决:Next.js API路由中unstable_getServerSession报"Cannot read properties of undefined (reading 'secret')"错误

问题分析

错误核心原因是你的pages/api/[...nextauth].js文件未导出供API路由调用的authOptions配置对象,而是直接导出了NextAuth初始化实例,导致API路由中导入的authOptions为undefined,进而触发读取secret属性失败的报错。

解决方案

步骤1:修改pages/api/[...nextauth].js,单独导出authOptions配置

将原代码中的授权配置抽离为独立的authOptions对象并导出,再用它初始化NextAuth:

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

// 单独导出授权配置对象,供API路由调用
export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
    // 可添加更多授权提供商
  ],
  secret: process.env.NEXTAUTH_SECRET,
};

export default NextAuth(authOptions);

步骤2:确认API路由的导入路径正确性

检查pages/api/tasks/[user]/[date]/index.js中authOptions的导入路径是否匹配你的文件结构,原代码中的import { authOptions } from "../../../auth/[...nextauth]";若对应pages/api/auth/[...nextauth].js则路径正确,否则需调整层级。

步骤3:验证环境变量有效性

确认.env文件中NEXTAUTH_SECRET、GOOGLE_ID、GOOGLE_SECRET已正确配置,开发环境下需重启Next.js开发服务器以加载最新环境变量。

优化后的API路由代码(可选,完善身份校验)

在获取session后添加认证校验,确保未授权用户无法访问:

import clientPromise from "../../../../../lib/mongodb";
import { authOptions } from "../../../auth/[...nextauth]";
import { unstable_getServerSession } from "next-auth/next";

export default async (req, res) => {
  const session = await unstable_getServerSession(req, res, authOptions);

  // 校验用户是否已认证
  if (!session) {
    return res.status(401).json({ error: "未授权访问" });
  }

  const { user, date } = req.query;
  try {
    const client = await clientPromise;
    const db = client.db();
    const tasks = await db
      .collection("tasks")
      .find({ user: user, taskDate: date })
      .sort({ startDate: -1 })
      .toArray();

    res.status(200).json({ tasks });
  } catch (err) {
    res.status(500).json({ error: "获取数据失败" });
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:00:56