0

我正在尝试在服务器端获取当前登录的 supabase 用户。

我曾尝试使用const user = supabase.auth.user();,但我总是得到null回应。

我也尝试过const user = supabase.auth.getUserByCookie(req),但它也会返回null。我认为是因为从钩子调用它时我没有向 api 发送 cookie。

我尝试将user.id钩子传递给 api,但 api 没有接收参数。

我也尝试过这种方法,但从未获取过令牌。它似乎不存在于 req.cookies 中。

    let supabase = createClient(supabaseUrl, supabaseKey);
    let token = req.cookies['sb:token'];
    if (!token) {
        return 
    }
    let authRequestResult = await fetch(`${supabaseUrl}/auth/v1/user`, {
        headers: {
            'Authorization': `Bearer ${token}`,
            'APIKey': supabaseKey
        }
    });
`

有谁知道如何在服务器端代码中获取当前登录用户?

4

1 回答 1

0

如果您需要在服务器端获取用户,则需要使用给定的 Next.js API 在服务器中设置 Auth Cookie。

// pages/api/auth.js
import { supabase } from "../path/to/supabaseClient/definition";

export default function handler(req, res) {
    if (req.method === "POST") {
        supabase.auth.api.setAuthCookie(req, res);
    } else {
        res.setHeader("Allow", ["POST"]);
        res.status(405).json({
            message: `Method ${req.method} not allowed`,
        });
    }
}

每次用户的状态发生变化时都需要调用这个端点,即事件SIGNED_INSIGNED_OUT

您可以在 _app.js 或可能在用户上下文文件中设置 useEffect。

// _app.js

import "../styles/globals.css";
import { supabase } from '../path/to/supabaseClient/def'

function MyApp({ Component, pageProps }) {

    useEffect(() => {
    const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
      handleAuthChange(event, session)
      if (event === 'SIGNED_IN') {
         // TODO: Actions to Perform on Sign In
      }
      if (event === 'SIGNED_OUT') {
         // TODO: Actions to Perform on Logout
      }
    })
    checkUser()
    return () => {
      authListener.unsubscribe()
    }
  }, [])

    return <Component {...pageProps} />;
}

async function handleAuthChange(event, session) {
    await fetch('/api/auth', {
      method: 'POST',
      headers: new Headers({ 'Content-Type': 'application/json' }),
      credentials: 'same-origin',
      body: JSON.stringify({ event, session }),
    })
  }

export default MyApp;

您现在可以使用状态处理此用户并将其传递给应用程序或您想要的任何方式。

您可以在任何 Next.js 页面中的服务器端获取用户

// pages/user_route.js

import { supabase } from '../path/to/supabaseClient/def'

export default function UserPage ({ user }) {

  return (
    <h1>Email: {user.email}</h1>
  )

}

export async function getServerSideProps({ req }) {
  const { user } = await supabase.auth.api.getUserByCookie(req)

  if (!user) {
    return { props: {}, redirect: { destination: '/sign-in' } }
  }

  return { props: { user } }
}

这是来自 Nader Dabit 的 YouTube 教程 - https://www.youtube.com/watch?v=oXWImFqsQF4
和他的 GitHub 存储库 - https://github.com/dabit3/supabase-nextjs-auth

于 2022-01-11T08:18:24.917 回答