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

NextAuth.js v5调用signIn函数触发CallbackRouteError求助

NextJS 14 + NextAuth Credentials登录触发CallbackRouteError问题

我是中初级开发者,正在给朋友开发基于NextJS 14 App目录的应用。因DrizzleORM兼容性问题,使用了Neon数据库和Prisma适配器。参考CodeWithAntonio的教程并做微调后,调用signIn函数时始终触发CallbackRouteError,反复排查仍未解决。

相关代码文件

auth.ts(根目录)

import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";

import { db } from "@/lib/db";
import authConfig from "@/auth.config";
import { getUserById } from "@/lib/user";
import { UserRole } from "@prisma/client";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
  },
  callbacks: {
    async signIn({ user, account }) {
      if (account?.provider !== "credentials") return true;

      return true;
    },
    async session({ token, session }) {
      if (token.sub && session.user) {
        session.user.id = token.sub;
      }

      if (token.role && session.user) {
        session.user.role = token.role as UserRole;
      }

      return session;
    },
    async jwt({ token }) {
      if (!token.sub) return token;

      // 从数据库获取token对应的用户数据
      const existingUser = await getUserById(token.sub);

      if (!existingUser) return token;

      token.role = existingUser.role;

      return token;
    },
  },
  adapter: PrismaAdapter(db),
  session: { strategy: "jwt", maxAge: 60 * 60 * 24 },
  ...authConfig,
});

auth.config.ts(根目录)

import bcrypt from "bcryptjs";

import type { NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";

import { LoginSchema } from "@/schemas";
import { getUserByEmail } from "./lib/user";

export default {
  providers: [
    Credentials({
      async authorize(credentials) {
        const validatedFields = LoginSchema.safeParse(credentials);

        if (validatedFields.success) {
          const { email, password } = validatedFields.data;

          // 通过邮箱从数据库获取用户数据
          const user = await getUserByEmail(email);

          if (!user || !user.password) return null;

          const passwordsMatch = await bcrypt.compare(password, user.password);

          if (passwordsMatch) return user;

          return null;
        }

        return null;
      },
    }),
  ],
} satisfies NextAuthConfig;

login.ts(登录Server Action)

"use server";

import * as z from "zod";

import { LoginSchema } from "@/schemas";
import { signIn } from "@/auth";
import { DEFAULT_LOGIN_REDIRECT } from "@/routes";
import { AuthError } from "next-auth";
import { getUserByEmail } from "@/lib/user";
import { generateVerificationToken } from "@/lib/tokens";

export const login = async (values: z.infer<typeof LoginSchema>) => {
  const validatedFields = LoginSchema.safeParse(values);

  if (!validatedFields.success) {
    return { error: "Invalid fields!" };
  }

  const { email, password } = validatedFields.data;

  // 通过邮箱从数据库获取用户数据
  const existingUser = await getUserByEmail(email);

  if (!existingUser || !existingUser.email || !existingUser.password) {
    return { error: "Your email and/or password are incorrect." };
  }

  if (!existingUser.email_verified) {
    // 为用户生成并返回验证token
    const verificationToken = await generateVerificationToken(
      existingUser.email
    );

    return { success: "Verification email sent!" };
  }

  try {
    await signIn("credentials", {
      email,
      password,
      // 当前跳转至/settings页面
      redirectTo: DEFAULT_LOGIN_REDIRECT,
    });
  } catch (error) {
    // 此处返回"CallbackRouteError"错误信息
    console.log(error);
    if (error instanceof AuthError) {
      switch (error.type) {
        case "CredentialsSignin":
          return { error: "Your email and/or password are incorrect." };
        default:
          return { error: "Something went wrong!" };
      }
    }
    throw error;
  }
};

报错信息

Read more at https://errors.authjs.dev/#credentialssignin
[auth][error] CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror
[auth][cause]: Error
    at Module.callback (webpack-internal:///(action-browser)/./node_modules/@auth/core/lib/actions/callback/index.js:226:23)
    at async AuthInternal (webpack-internal:///(action-browser)/./node_modules/@auth/core/lib/index.js:66:24)
    at async Auth (webpack-internal:///(action-browser)/./node_modules/@auth/core/index.js:126:34)
    at async signIn (webpack-internal:///(action-browser)/./node_modules/next-auth/lib/actions.js:51:17)
    at async $$ACTION_0 (webpack-internal:///(action-browser)/./actions/login.ts:46:9)
    at async F:\lng-v3\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:39:418
    at async rw (F:\lng-v3\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:38:7978)
    at async r4 (F:\lng-v3\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:41:1251)
    at async doRender (F:\lng-v3\node_modules\next\dist\server\base-server.js:1438:30)
    at async cacheEntry.responseCache.get.routeKind (F:\lng-v3\node_modules\next\dist\server\base-server.js:1599:28)
    at async DevServer.renderToResponseWithComponentsImpl (F:\lng-v3\node_modules\next\dist\server\base-server.js:1507:28)
    at async DevServer.renderPageComponent (F:\lng-v3\node_modules\next\dist\server\base-server.js:1931:24)
    at async DevServer.renderToResponseImpl (F:\lng-v3\node_modules\next\dist\server\base-server.js:1969:32)
    at async DevServer.pipeImpl (F:\lng-v3\node_modules\next\dist\server\base-server.js:920:25)
    at async NextNodeServer.handleCatchallRenderRequest (F:\lng-v3\node_modules\next\dist\server\next-server.js:272:17)
    at async DevServer.handleRequestImpl (F:\lng-v3\node_modules\next\dist\server\base-server.js:816:17)
    at async F:\lng-v3\node_modules\next\dist\server\dev\next-dev-server.js:339:20
    at async Span.traceAsyncFn (F:\lng-v3\node_modules\next\dist\trace\trace.js:154:20)
    at async DevServer.handleRequest (F:\lng-v3\node_modules\next\dist\server\dev\next-dev-server.js:336:24)
    at async invokeRender (F:\lng-v3\node_modules\next\dist\server\lib\router-server.js:174:21)
    at async handleRequest (F:\lng-v3\node_modules\next\dist\server\lib\router-server.js:353:24)
    at async requestHandlerImpl (F:\lng-v3\node_modules\next\dist\server\lib\router-server.js:377:13)
    at async Server.requestListener (F:\lng-v3\node_modules\next\dist\server\lib\start-server.js:141:13)
[auth][details]: {
  "provider": "credentials"
}

已多次对照教程排查未找到问题,如需更多信息可提供,恳请帮忙解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:50:54