Bre*_*ami 2 next.js supabase supabase-database
我试图在服务器端获取当前登录的 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
}
});
`
Run Code Online (Sandbox Code Playgroud)
有谁知道如何在服务器端代码中获取当前登录的用户?
小智 5
如果您需要在服务器端获取用户,则需要使用给定的 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`,
});
}
}
Run Code Online (Sandbox Code Playgroud)
每次用户状态发生变化(即事件SIGNED_IN和事件)时都需要调用此端点SIGNED_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;
Run Code Online (Sandbox Code Playgroud)
您现在可以使用状态处理该用户并将其传递给应用程序或以您想要的任何方式传递。
您可以在任何 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 } }
}
Run Code Online (Sandbox Code Playgroud)
这是来自 Nader Dabit 的 YouTube 教程 - https://www.youtube.com/watch?v=oXWImFqsQF4
和他的 GitHub 存储库 - https://github.com/dabit3/supabase-nextjs-auth
| 归档时间: |
|
| 查看次数: |
9847 次 |
| 最近记录: |