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

使用next-auth实现Google OAuth登录跳转错误的排查及解决

问题:NextAuth Google OAuth登录跳转至错误页面

尝试用NextAuth实现Google OAuth登录,点击「使用Google登录」按钮后,页面直接跳转到http://localhost:3000/api/auth/error,预期应跳转至Google的OAuth授权页面。

控制台错误信息

[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error NetworkError when attempting to fetch resource.
Object { error: {…}, url: "/api/auth/providers", message: "NetworkError when attempting to fetch resource." }

已尝试的排查步骤

  • 重置GOOGLE_CLIENT_ID、GOOGLE_CLIENT_SECRET及NEXTAUTH_SECRET
  • 在[...nextauth].ts文件的providers上方添加secret: NEXTAUTH_SECRET配置(尽管文档说明无需此操作)
  • 直接在地址栏输入localhost:3000/api/auth/callback/google可正常跳转至Google授权页,且能在首页获取session对象
  • 将next-auth从4.14.0版本升级至4.15.0
  • 清除http://localhost:3000的Cookie和会话数据
  • 在Vercel部署项目并配置正确的环境变量,将域名添加至Google凭据,尝试多设备登录
  • 在多款浏览器及无痕模式下测试登录
  • 尝试无参数调用signIn()
  • 在StackOverflow和Next.js官方GitHub问题区查找并尝试多种解决方案

相关代码及配置

/client/pages/api/auth/[...nextauth].ts

import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
};

export default NextAuth(authOptions);

/client/pages/login.tsx 中OAuth组件及按钮配置

<OAuth
  company="Google"
  handleLogin={() =>
    signIn("google", { callbackUrl: "http://localhost:3000/" })
  }
/>

/client/.env 文件

GOOGLE_CLIENT_ID=***********
GOOGLE_CLIENT_SECRET=***********

NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=122a918b879a0d7e331c0795f435d084

Google开发者凭据配置

  • 已将http://localhost:3000/api/auth/callback/google添加至「授权重定向URI」
  • 已将http://localhost:3000添加至「授权JavaScript来源」

解决方案

修改handleLogin方法,添加e.preventDefault()阻止默认行为:

<OAuth
  company="Google"
  handleLogin={(e) => {
    e.preventDefault();
    signIn("google", { callbackUrl: REDIRECT_URL_AFTER_SIGN_IN });
  }}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:25:41