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

Supabase+Next.js App Router服务端认证:layout.tsx中Session为null问题

核心问题

你在Next.js App Router的根Layout(服务器组件)中使用的Supabase客户端未正确从请求Cookie中读取认证信息,导致getSession()无法识别已存在的sb-access-token。

修复步骤

1. 创建服务器端专用Supabase客户端

App Router的服务器组件必须使用带Cookie配置的专属Supabase客户端,而非客户端侧的全局实例。新建工具文件:

// app/utils/supabase/server.ts
import { createServerComponentClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';

export const getServerSupabase = () => {
  return createServerComponentClient({ cookies });
};

2. 在RootLayout中调用服务器端客户端获取Session

替换原代码中的Supabase实例,改用服务器端客户端执行getSession():

import { getServerSupabase } from '@/app/utils/supabase/server';

export default async function RootLayout({ children }: RootLayoutProps) {
  const supabase = getServerSupabase();
  
  const {
    data: { session },
    error,
  } = await supabase.auth.getSession();

  if (error) {
    console.error("Error fetching session:", error.message);
  } else {
    console.log("Session:", session);
  }

  return (
    <html lang="en">
      <body>
        <TopNav />
        {children}
      </body>
    </html>
  );
}

3. 额外排查点

  • 确认Supabase控制台Auth > URL配置中的Site URL与你的Next.js应用URL完全匹配(含http/https、端口)
  • 检查sb-access-token的过期时间:可在浏览器开发者工具的Application > Cookies中查看Expires字段
  • 确保未禁用Supabase的Cookie认证模式(默认启用)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:03:09