使用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', })
排查方向及解决方案
环境变量配置错误
- NextAuth的
secret不应使用NEXT_PUBLIC_前缀的变量,这个前缀会把变量暴露给客户端,改用NEXTAUTH_SECRET。部署时确保Vercel上正确配置该变量,值可通过openssl rand -hex 32生成。 - 检查
DATABASE_URL是否在Vercel上正确配置,同时确认托管数据库(如Supabase、PlanetScale)已将Vercel的IP加入访问白名单。
- NextAuth的
Prisma Adapter与JWT策略冲突
- 凭证登录+JWT会话策略下,
PrismaAdapter并非必需,它主要用于OAuth登录或数据库存储会话的场景。可以暂时移除adapter: PrismaAdapter(prisma),测试是否还会出现超时问题。
- 凭证登录+JWT会话策略下,
数据库查询超时
- 504错误多因请求超时,检查数据库
email字段是否有唯一索引(Prisma schema中设为unique会自动生成),提升查询速度。 - 确保Vercel部署区域与数据库区域接近,减少网络延迟。
- 504错误多因请求超时,检查数据库
Vercel函数超时设置
- Vercel Serverless Functions默认超时10秒,若数据库查询或bcrypt验证耗时较长,可在项目设置中把函数超时调整至最大60秒。
优化
authorize函数逻辑- 提前判断
credentials的完整性,避免无效数据库请求;可考虑缓存高频查询结果,减少数据库压力。
- 提前判断
内容的提问来源于stack exchange,提问作者Lindrit Sulaj
相关产品推荐
相关产品推荐

