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

使用next-auth凭证登录失败(部署环境异常)求助

NextAuth + Prisma 部署后凭证登录504错误排查

我是NextAuth和Prisma的新手,正在搭建一个结合二者实现身份验证的网站。开发模式下代码运行正常,但部署到Vercel后使用凭证登录时,控制台出现两个错误:

  • Failed to load resource: the server responded with a status of 504()
  • Uncaught (in promise) SyntaxError: Unexpected token 'A', "An error o"... is not valid JSON

查看Vercel的Runtime Logs,发现[POST]/api/auth/callback/credentials请求出现问题。以下是相关代码:

代码文件

app/api/auth/[...nextauth]/options.ts

import type { NextAuthOptions } from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { PrismaAdapter } from '@next-auth/prisma-adapter'
import bcrypt from 'bcrypt'

import prisma from '@/lib/prisma' 

export const options: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      id: "credentials",
      name: 'credentials',
      credentials: {
        email: {
          label: 'Email',
          type: 'email',
        },
        password: {
          label: "Password",
          type: 'password'
        }
      },
      async authorize(credentials) {
        if (!credentials?.email && !credentials?.password) {
          throw new Error("Please enter both fields")
        }

        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("Password is incorrect")
        };

        return user;
      }
    })
  ],
  adapter: PrismaAdapter(prisma),
  pages: {
    signIn: '/'
  },
  session: {
    strategy: 'jwt'
  },
  secret: process.env.NEXT_PUBLIC_NEXTAUTH_SECRET,
}

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

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

const handler = NextAuth(options);

export { handler as GET, handler as POST }

登录页面调用代码

客户端组件中使用signIn函数的方式:

signIn("credentials", {
  email: 'random@email.com',
  password: 'random-password',
})

排查方向及解决方案

  1. 环境变量配置错误

    • NextAuth的secret不应使用NEXT_PUBLIC_前缀的变量,这个前缀会把变量暴露给客户端,改用NEXTAUTH_SECRET。部署时确保Vercel上正确配置该变量,值可通过openssl rand -hex 32生成。
    • 检查DATABASE_URL是否在Vercel上正确配置,同时确认托管数据库(如Supabase、PlanetScale)已将Vercel的IP加入访问白名单。
  2. Prisma Adapter与JWT策略冲突

    • 凭证登录+JWT会话策略下,PrismaAdapter并非必需,它主要用于OAuth登录或数据库存储会话的场景。可以暂时移除adapter: PrismaAdapter(prisma),测试是否还会出现超时问题。
  3. 数据库查询超时

    • 504错误多因请求超时,检查数据库email字段是否有唯一索引(Prisma schema中设为unique会自动生成),提升查询速度。
    • 确保Vercel部署区域与数据库区域接近,减少网络延迟。
  4. Vercel函数超时设置

    • Vercel Serverless Functions默认超时10秒,若数据库查询或bcrypt验证耗时较长,可在项目设置中把函数超时调整至最大60秒。
  5. 优化authorize函数逻辑

    • 提前判断credentials的完整性,避免无效数据库请求;可考虑缓存高频查询结果,减少数据库压力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:22:35