簡(jiǎn)介
- 這個(gè)實(shí)際上是一個(gè)服務(wù)端調(diào)用的方法煌妈,這個(gè)方法的返回值會(huì)回填到頁(yè)面的 Props 參數(shù)中
- 舉例:有一個(gè)頁(yè)面 pages/user.tsx
import { getSession, signOut } from "next-auth/react";
import {GetServerSideProps} from "next";
import {Session} from "next-auth";
// gets a prop from getServerSideProps
type MyPara = {
user: any,
domain: string,
}
function User(data: MyPara) {
return (
<div>
<h4>User session: {data.domain}</h4>
<pre>{JSON.stringify(data.user, null, 2)}</pre>
<button onClick={() => signOut({ callbackUrl: "/signin" })}>Sign out</button>
</div>
);
}
export default User;
export const getServerSideProps: GetServerSideProps<{user: any}> = async (context) => {
const session = await getSession(context);
// redirect if not authenticated
if (!session) {
return {
redirect: {
destination: "/signin",
permanent: false,
},
};
}
return {
props: { user: session.user, domain: 'cancanyou.com' },
};
}
-
這里面 getServerSideProps 的返回值 props 段落會(huì)回傳給 User(data) ,可以看到最終的頁(yè)面輸出: