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

如何解决NextAuth的/api/auth/error?error=Configuration配置错误问题

问题描述

我正在学习Next.js并尝试使用NextAuth,当打开受NextAuth保护的/features页面时,会被重定向到/api/auth/error?error=Configuration。Stack Overflow上的回答都提示需添加密钥,但我已经添加了该密钥。尝试登录后再次访问/features页面,仍然会被重定向到http://localhost:3000/api/auth/error?error=Configuration。

相关代码文件

middleware.js

export { default } from "next-auth/middleware";

export const config ={matcher:["/features"]};

[...nextauth].js

import NextAuth from "next-auth";
import { options } from "./options";

export default NextAuth(options);

options.js

import DiscordProvider from "next-auth/providers/discord";
import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";

export const options = {
    providers: [
      GithubProvider({
        clientId: process.env.GITHUB_ID,
        clientSecret: process.env.GITHUB_SECRET,
      }),
      DiscordProvider({
        clientId: process.env.DISCORD_CLIENT_ID,
        clientSecret: process.env.DISCORD_CLIENT_SECRET,
      }),
      CredentialsProvider({
        name: "Credentials",
        credentials: {
          username: { label: "Username", type: "text", placeholder: "awesome-username" },
          password: { label: "Password", type: "password",placeholder:"your password" },
        },
        async authorize(credentials) {
          const user = { id: 1, name: "vaibhav", password: "next" };
          //   const res = await fetch("/your/endpoint", {
          //     method: 'POST',
          //     body: JSON.stringify(credentials),
          //     headers: { "Content-Type": "application/json" }
          //   })
          //   const user = await res.json()
          if (
            credentials?.username === user.name &&
            credentials.password === user.password
          )
            return user;
          return null;
        },
      }),
    ],
    secret: process.env.NEXT_AUTH_SECRET,
  };

排查与解决方案

  • 验证环境变量有效性:
    • 检查.env文件中NEXT_AUTH_SECRET、GITHUB_ID、GITHUB_SECRET、DISCORD_CLIENT_ID、DISCORD_CLIENT_SECRET的拼写是否完全正确,注意变量名大小写(比如NEXT_AUTH_SECRET不能写成NEXTAUTH_SECRET)。
    • 修改环境变量后,必须重启Next.js开发服务器,否则新的变量不会生效。
  • 检查CredentialsProvider逻辑:
    • 登录时输入的用户名和密码必须和代码中硬编码的vaibhav、next完全匹配,包括大小写。
    • 确保authorize函数返回的用户对象包含id字段,这是NextAuth要求的必填字段。
  • 开启调试日志定位问题:
    • 启动开发服务器时添加调试参数:NEXTAUTH_DEBUG=true npm run dev,控制台会输出NextAuth的详细运行日志,能直接看到配置错误的具体原因。
  • 确认文件位置与版本兼容性:
    • 确保middleware.js位于项目根目录(Pages Router)或app目录下(App Router),位置错误会导致中间件不生效。
    • 检查package.json中next-auth的版本,若使用v4版本,当前配置结构是合规的;若版本不兼容,尝试升级到最新稳定版或降级到适配版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:35:24