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

Next.js 13使用@react-oauth/google报错:Cannot read properties of null (reading 'useState')

在Next.js 13中正确使用@react-oauth/google实现Google OAuth认证

问题原因

你遇到的TypeError: Cannot read properties of null (reading 'useState')错误,本质是**@react-oauth/google依赖React客户端特性(如useState),但被渲染在服务器组件中**。Next.js 13的App Router默认所有组件都是服务器组件,而服务器组件不支持React Hooks。

解决方案

1. 用客户端组件包裹GoogleOAuthProvider(App Router场景)

Next.js 13 App Router下,必须将GoogleOAuthProvider放在标记为客户端组件的文件中:

  • 创建app/providers/GoogleAuthProvider.tsx文件:
'use client';

import { GoogleOAuthProvider } from '@react-oauth/google';

type Props = {
  children: React.ReactNode;
};

export default function GoogleAuthProvider({ children }: Props) {
  return (
    <GoogleOAuthProvider clientId="你的Google Client ID">
      {children}
    </GoogleOAuthProvider>
  );
}
  • 在根布局app/layout.tsx中引入并包裹整个应用:
import GoogleAuthProvider from './providers/GoogleAuthProvider';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="zh-CN">
      <body>
        <GoogleAuthProvider>{children}</GoogleAuthProvider>
      </body>
    </html>
  );
}

2. 在客户端组件中使用Google登录按钮

所有调用Google登录组件的代码,都需要放在客户端组件内:
比如创建app/login/page.tsx:

'use client';

import { GoogleLogin } from '@react-oauth/google';
import jwt_decode from 'jwt-decode';

export default function LoginPage() {
  const handleSuccess = (response: any) => {
    const userInfo = jwt_decode(response.credential);
    // 这里处理用户信息,比如传递给后端验证
    console.log(userInfo);
  };

  const handleError = () => {
    console.log('Google登录失败');
  };

  return (
    <div>
      <h1>用户登录</h1>
      <GoogleLogin
        onSuccess={handleSuccess}
        onError={handleError}
        useOneTap
      />
    </div>
  );
}

3. Pages Router场景(旧路由系统)

如果仍使用Pages Router(pages/_app.tsx),直接在_app.tsx中配置即可,该文件默认是客户端组件:

import { GoogleOAuthProvider } from '@react-oauth/google';
import type { AppProps } from 'next/app';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <GoogleOAuthProvider clientId="你的Google Client ID">
      <Component {...pageProps} />
    </GoogleOAuthProvider>
  );
}

额外注意事项

  • 安装必要依赖:npm install @react-oauth/google jwt-decode(jwt-decode用于解析Google返回的用户凭证)
  • 确保Google Cloud Console中已正确配置Client ID,添加允许的域名(本地开发需包含http://localhost:3000)
  • 所有与Google OAuth相关的逻辑必须放在客户端组件内,禁止在服务器组件中调用相关API

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:55:14