简介
- 这个实际上是一个服务端调用的方法,这个方法的返回值会回填到页面的 Props 参数中
- 举例:有一个页面 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 段落会回传给 User(data) ,可以看到最终的页面输出: