Next.js NextAuth CredentialsProvider开发服务器报Bad Gateway问题
问题描述
本地环境运行NextAuth的CredentialsProvider认证功能正常,但部署到开发服务器后,调用https://dev1.mydevserver.us/api/auth/callback/credentials接口时出现POST ... bad gateway错误,且服务器无相关日志记录。已正确设置NEXTAUTH_URL为https://dev1.mydevserver.us/,同时GoogleProvider与AppleProvider使用相同URL可正常工作。
相关代码
NextAuth配置代码
CredentialsProvider({ name: "Credentials", async authorize(credentials, req) { try { const response = await axios.post( "https://dev1.mydevserver.us/auth/api/v1/signin", { email: credentials.email, password: credentials.password, apiKey: process.env.GURU_BOT_API_KEY, }, { headers: { "Content-Type": "application/json", }, } ); if ( response.data.statusCode === 201 || response.data.statusCode === 200 ) { const user = response.data; if (user) { return user; } return null; } else { throw new Error("Invalid Credentials"); } } catch (error) { throw new Error("Invalid email or password"); } }, }), ], cookies: { pkceCodeVerifier: { name: "next-auth.pkce.code_verifier", options: { httpOnly: true, sameSite: "none", path: "/", secure: true, }, }, }, callbacks: { async jwt({ token, account, user }) { if (account) { token = Object.assign({}, token, { access_token: account.access_token, id_token: account.id_token, refresh_token: account.refresh_token, provider: account.provider, user: user, }); } return token; }, async session({ session, token, user }) { if (session) { session = Object.assign({}, session, { access_token: token.access_token, id_token: token.id_token, refresh_token: token.refresh_token, provider: token.provider, user: token.user, }); } return session; }, }, session: { strategy: "jwt"},
UI调用代码
const status = await signIn("credentials", { redirect: false, email: email, password: password, callbackUrl: "/", }); if (status.success) { setLoading(false); router.push("/"); } if (status.error) { setError(status.error); }
可能原因及排查方向
1. 内部API请求的网络连通性问题
在authorize方法中,你直接调用了https://dev1.mydevserver.us/auth/api/v1/signin这个内部接口。部署到服务器后,可能存在以下情况:
- 服务器防火墙规则限制,禁止内部发起对该域名的请求
- 内网DNS解析失败,无法解析
dev1.mydevserver.us - 容器化部署场景下,容器网络无法访问外部/内部域名
排查:在服务器上执行curl -X POST https://dev1.mydevserver.us/auth/api/v1/signin -H "Content-Type: application/json" -d '{"email":"test@example.com","password":"test","apiKey":"your_key"}',查看是否能正常响应。
2. 环境变量未正确加载
代码中依赖process.env.GURU_BOT_API_KEY,如果服务器上该环境变量未配置、配置错误或未被Next.js正确加载,会导致内部signin接口请求失败。而Google/Apple Provider不依赖该变量,因此不受影响。
排查:在服务器上打印环境变量(如echo $GURU_BOT_API_KEY),或在authorize方法中临时添加日志输出该变量的值,确认是否正确获取。
3. 内部API请求超时
内部signin接口响应时间过长,导致NextAuth的callback接口超时,被服务器反向代理(如Nginx)判定为Bad Gateway。本地环境网络延迟低,不会触发超时,但服务器环境可能因网络或接口性能问题导致超时。
排查:在服务器上用curl请求内部signin接口,记录响应耗时;检查反向代理的超时配置(如Nginx的proxy_connect_timeout、proxy_read_timeout)。
4. Cookie配置兼容性问题
当前Cookie配置中pkceCodeVerifier的sameSite设为none且secure: true,虽然适用于跨域场景,但部分服务器环境可能对Cookie属性有严格限制,或HTTPS证书存在异常,导致Cookie无法正常传递。不过因Google/Apple Provider正常,此可能性较低。
排查:临时将sameSite改为lax(非跨域场景下),或检查服务器HTTPS证书是否有效、是否配置正确。
内容的提问来源于stack exchange,提问作者Sahil Singh

