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

SupabaseAuthClient无session属性的TypeError构建错误求助

解决Next.js 14.1.0集成Supabase时的session类型错误

问题场景

用Next.js 14.1.0开发项目,集成Supabase做身份验证,执行npm run build时触发类型错误:Type error: Property 'session' does not exist on type 'SupabaseAuthClient',错误出现在page.tsx第17行调用supabase.auth.session()的位置。

完整报错信息

PS E:\open-source\my-project>npm run build

nextjs@0.1.0 build
next build

▲ Next.js 14.1.0

  • Environments: .env

Creating an optimized production build ...
Compiler edge-server unexpectedly exited with code: null and signal: SIGTERM
✓ Compiled successfully
Linting and checking validity of types ...Failed to compile.

./app/page.tsx:17:62
Type error: Property 'session' does not exist on type 'SupabaseAuthClient'.

15 | const fetchSession = async () => {
16 | try {

17 | const { data: session, error } = await supabase.auth.session();
| ^
18 | if (error) {
19 | throw error;
20 | }
Linting and checking validity of types .
PS E:\open-source\my-project>

涉及的page.tsx代码

"use client";
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Session } from "@supabase/supabase-js";
import { Auth } from "@supabase/auth-ui-react";
import { ThemeSupa } from "@supabase/auth-ui-shared";
import { supabase } from "@/lib/supabase";

const Home: React.FC = () => {
  const [session, setSession] = useState<Session | null>(null);
  const [userData, setUserData] = useState<any>(null);

  useEffect(() => {
    const fetchSession = async () => {
      try {
        const { data: session, error } = await supabase.auth.session();
        if (error) {
          throw error;
        }
        setSession(session);

        if (session) {
          // If session exists, fetch user data
          const userDataResponse = await fetchUserData(session.access_token);
          setUserData(userDataResponse);
          console.log("User data:", userDataResponse);
        }
      } catch (error: any) {
        console.error("Error fetching session:", error.message);
      }
    };

    const authListener = supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session);
    });

    fetchSession();

    return () => {
      authListener.data.subscription.unsubscribe();
    };
  }, []);

  const fetchUserData = async (accessToken: string) => {
    try {
      const response = await axios.get("http://localhost:3001/users/me", {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      });
      return response.data;
    } catch (error: any) {
      console.error("Error fetching user data:", error.message);
      return null;
    }
  };

  return (
    <div>
      {!session ? (
        <div className="form-container">
          <div className="flex flex-wrap">
            <div className="w-full px-4">
              <div className="wow fadeInUp relative mx-auto max-w-[525px] overflow-hidden rounded-lg bg-white py-14 px-8 sm:px-12 md:px-[60px]">
                <Auth
                  supabaseClient={supabase}
                  appearance={{ theme: ThemeSupa }}
                />
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div className="container mx-auto px-4">
          <div className="p-4">
            <h2 className="text-2xl text-center font-bold text-blue-800">
              Welcome back, {session.user.user_metadata.name}!
            </h2>

            <div className="user-info-container border-2 shadow-lg mt-8">
              <h3 className="text-lg font-semibold">User Information</h3>
              <div className="flex items-center mt-4">
                <img
                  className="w-20 h-20 rounded-full mr-4"
                  src={session.user.user_metadata.avatar_url}
                  alt="Avatar"
                />
                <div>
                  <p className="text-gray-600">
                    <strong>Name:</strong> {session.user.user_metadata.name}
                  </p>
                  <p className="text-gray-600 py-2">
                    <strong>Email:</strong> {session.user.email}
                  </p>
                  <p className="text-gray-600">
                    <strong>Last Sign In:</strong>{" "}
                    {session.user.last_sign_in_at}
                  </p>
                </div>
              </div>
            </div>

            <div className="mt-8 grid grid-cols-1 sm:grid-cols-2 gap-8">
              <div className="featureItem bg-white rounded-lg border-2 shadow-lg p-6">
                <h3 className="text-xl font-bold mb-2">
                  Collaborative Projects
                </h3>
                <p className="text-gray-600 mb-4">
                  Work on projects related to human improvement applications and
                  startups.
                </p>
                <button className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition duration-300 ease-in-out">
                  Explore Projects
                </button>
              </div>
              <div className="featureItem bg-white rounded-lg border-2 shadow-lg p-6">
                <h3 className="text-xl font-bold mb-2">User Engagement</h3>
                <p className="text-gray-600 mb-4">
                  Create an interactive learning experience with robust user
                  engagement features.
                </p>
                <button className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition duration-300 ease-in-out">
                  Engage Now
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Home;

解决方案

这个错误源于Supabase JS SDK版本差异:你用的是v2版本,但supabase.auth.session()是v1的API,v2已经移除了这个方法,替换成supabase.auth.getSession()。

修改fetchSession函数中的对应代码:

// 原代码
const { data: session, error } = await supabase.auth.session();

// 修改为
const { data: { session }, error } = await supabase.auth.getSession();

注意:v2的getSession()返回结构是{ data: { session }, error },比v1多一层解构,必须按这个格式获取session。

修改后的完整fetchSession函数:

const fetchSession = async () => {
  try {
    const { data: { session }, error } = await supabase.auth.getSession();
    if (error) {
      throw error;
    }
    setSession(session);

    if (session) {
      // If session exists, fetch user data
      const userDataResponse = await fetchUserData(session.access_token);
      setUserData(userDataResponse);
      console.log("User data:", userDataResponse);
    }
  } catch (error: any) {
    console.error("Error fetching session:", error.message);
  }
};

改完之后,类型错误就会消失,npm run build就能正常完成。

补充说明

如果你的Supabase SDK是v1版本,session()方法是有效的,但v2已经全面替代v1,建议升级到最新版SDK并使用v2的API。如果非要用v1,得确保依赖版本匹配,但不推荐长期使用旧版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:02:09