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

Next.js+Supabase认证报错:TypeError: Cannot read properties of undefined (reading 'user')

问题分析与解决

报错原因

你错误地从@supabase/supabase-js直接导入auth对象,但该包并未导出这个顶级对象,导致auth为undefined,调用auth.user()时触发"Cannot read properties of undefined (reading 'user')"错误。正确的认证操作应该通过你在supabaseConfig.js中初始化好的supabase实例来完成。

解决方法

修改useAuthentication.js文件,移除无效的auth导入,改用已初始化的supabase实例的auth模块来获取用户信息:

修改后的代码

import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { supabase } from '../supabase/supabaseConfig';

const useAuthentication = () => {
  const router = useRouter();

  useEffect(() => {
    const checkIfUserIsLoggedIn = async () => {
      // 使用supabase实例的auth模块获取用户
      const { data: { user }, error } = await supabase.auth.getUser();
      // 处理可能的错误
      if (error) {
        console.error('获取用户信息失败:', error);
        return;
      }
      if (!user) {
        router.push('/login');
      }
    };

    checkIfUserIsLoggedIn();
  }, [router]);

  return null;
};

export default useAuthentication;

补充说明

  • 若使用旧版Supabase JS SDK(v1),可改用同步方法supabase.auth.user()替代getUser(),但推荐升级至新版并使用异步的getUser(),它能更可靠地获取当前用户状态。
  • 确保supabaseConfig.js中的环境变量NEXT_PUBLIC_SUPABASEURL和NEXT_PUBLIC_SUPABASEKEY已正确配置在项目环境中(如.env.local文件)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 19:37:13