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

NextAuth登录跳转api/auth/error 404问题求助

NextAuth登录跳转/api/auth/error出现404的解决方法

针对你遇到的登录跳转404问题,结合你使用的Next.js 13.4.10、NextAuth 4.22.3技术栈,给出以下排查和修复方案:


1. 修正NextAuth路由文件路径(核心问题)

从你的@/app/libs/prismadb路径可判断项目启用了App Router,NextAuth的路由文件不能放在pages/api/auth/[...nextauth].ts,必须适配App Router的API路由规则:

  • 创建新路径:app/api/auth/[...nextauth]/route.ts
  • 将原pages/api/auth/[...nextauth].ts的内容迁移到该文件,并修改导出方式:
import NextAuth from "next-auth";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import prisma from '@/app/libs/prismadb';
import GithubProvider from 'next-auth/providers/github';
import GoogleProvider from 'next-auth/providers/google';
import bcrypt from 'bcrypt';
import CredentialsProvider from "next-auth/providers/credentials";
import { AuthOptions } from "next-auth";

export const authOptions: AuthOptions = {
  // 保留你原有的所有配置
  adapter: PrismaAdapter(prisma),
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID as string,
      clientSecret: process.env.GITHUB_SECRET as string
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string
    }),
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: {label: 'email', type: 'text'},
        password: {label: 'password', type: 'password'},
      },
      async authorize(credentials) {
        console.log(credentials);

        if (!credentials?.email || !credentials?.password) {
          throw new Error('Invalid credentials');
        }

        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email
          }
        });

        if (!user || !user?.hashedPassword) {
          throw new Error('Invalid credentials');
        }

        const isCorrectPassword = await bcrypt.compare(
          credentials.password,
          user.hashedPassword
        );

        if (!isCorrectPassword) {
          throw new Error('Invalid credentials');
        }

        return user;
      }
    })
  ],
  pages: {
    signIn: '/',
    error: '/auth/error', // 新增错误页配置
  },
  debug: process.env.NODE_ENV === 'development',
  session: {
    strategy: 'jwt',
  },
  secret: process.env.NEXTAUTH_SECRET,
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

2. 创建自定义错误页避免404

按照authOptions中配置的error: '/auth/error',创建对应页面:

  • 若使用App Router:创建app/auth/error/page.tsx,示例内容:
export default function ErrorPage() {
  return (
    <div className="container mx-auto p-4">
      <h1>登录错误</h1>
      <p>请检查你的账号密码是否正确</p>
    </div>
  );
}

3. 排查CredentialsProvider验证逻辑

  1. 打开浏览器控制台,查看Network面板,确认/api/auth/callback/credentials请求是否正常发起
  2. 查看终端Node日志,检查是否有Invalid credentials的输出:
    • 若有该日志,说明是账号密码验证失败,需检查注册时密码加密逻辑、数据库中hashedPassword字段是否正确存储
    • 若无该日志,说明请求未到达NextAuth,需再次检查路由文件路径是否正确

4. 完善环境变量配置

在.env文件中补充NEXTAUTH_URL,避免NextAuth生成错误的回调地址:

NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=你的自定义密钥
# 其他已有的MongoDB、第三方登录配置

5. 验证Prisma用户模型

确保你的Prisma Schema中User模型包含hashedPassword字段:

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String    @unique
  emailVerified DateTime?
  hashedPassword String?
  image         String?
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:57:08