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

NextAuth.js Credentials Provider登录报错:fetch失败排查

NextAuth.js Credentials Provider登录时fetch失败错误排查

登录时触发以下错误:

[auth][error] CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror
[auth][cause]: TypeError: fetch failed

相关代码

app/lib/auth.js

import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";

const URL = process.env.NEXT_PUBLIC_API_URL;
const Token = process.env.NEXT_PUBLIC_TOKEN;

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Credentials({
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
      },
      authorize: async (credentials) => {
        const { email, password } = credentials;
        console.log(email, password);
        console.log(`${URL}auth/jwt/create/`);
        const body = JSON.stringify({ email, password });
        const res = await fetch(`${URL}auth/jwt/create/`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body,
        });

        if (!res.ok) {
          throw new Error("Failed to sign in");
        } else {
          const data = await res.json();
          return data;
        }
      },
    }),
  ],
});

登录组件

import { signIn } from "@/app/lib/auth";
import { executeAction } from "../lib/executeAction";

function Page() {
  return (
    <main>
      <form
        action={async (formData) => {
          "use server";
          await executeAction({
            actionFn: async () => {
              await signIn("credentials", formData);
            },
          });
        }}
      >
        <h1>Sign in</h1>
        <input name="email" type="email" required />
        <input name="password" type="password" required />
        <button type="submit">Sign in</button>
      </form>
    </main>
  );
}

export default Page;

app/api/auth/[...nextauth]/route.js

import { handlers } from "@/app/lib/auth";
export const { GET, POST } = handlers;

已完成的排查

  • .env.local文件中NEXT_PUBLIC_API_URL和NEXT_PUBLIC_TOKEN配置无误
  • 后端URL及auth/jwt/create/端点路径正确
  • 后端服务运行正常,可通过Postman/cURL正常访问

疑问

目前authorize方法内的fetch请求仍失败,请问可能的原因是什么?该如何解决?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 14:52:14