Next-auth:虽然从 getServerSideProps 传递,但页面的属性未定义

Tax*_*xel 3 typescript reactjs next.js next-auth

我试图将我从getSession(使用next-auth)获得的会话作为道具传递给页面。我知道我可以useSession()在组件中使用,但根据我的理解,这应该也可以工作,但我不明白为什么它不能。

这似乎是与这个问题类似的问题,但没有答案。

这是我的非常基本的pages/settings.tsx

import { Card, CardContent, Typography } from "@mui/material";
import { User } from "@prisma/client";
import { GetServerSideProps, NextPage } from "next";
import { getSession } from "next-auth/react";

interface SettingsProps {
  user: User,
}

const Settings : NextPage<SettingsProps> = ({user})=>{
  // in here, user is always undefined...
  return (
    <Card>
      <CardContent>      
        <Typography variant="h3">Settings</Typography>
        <Typography>UserId: {user.id}</Typography>
        <Typography>Created: {(new Date(user.createdAt)).toLocaleDateString()}</Typography>
      </CardContent>
      
    </Card>
  );
};

export const getServerSideProps: GetServerSideProps<SettingsProps> =  async (context) =>{
  const session = await getSession(context);

  if (!session) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    };
  }

  console.log(session.user); // this works and logs the user

  return {
    props: { user: session.user },
  };
};

export default Settings;
Run Code Online (Sandbox Code Playgroud)

我已经next-auth像这样增强了会话类型(types/next-auth.d.ts):

import { User } from "@prisma/client";
import NextAuth from "next-auth";

declare module "next-auth" {
  /**
   * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
   */
  interface Session {
    user: User
  }
}
Run Code Online (Sandbox Code Playgroud)

根据我对 React 和 NextJs 的理解,上面的代码应该可以完美地工作,但是当访问页面时我得到

TypeError: Cannot read properties of undefined (reading 'id')
  13 |       <CardContent>      
  14 |         <Typography variant="h3">Settings</Typography>
> 15 |         <Typography>UserId: {user.id}</Typography>
     |                                  ^
  16 |         <Typography>Created: {(new Date(user.createdAt)).toLocaleDateString()}</Typography>
  17 |       </CardContent>
  18 |       

Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Amr*_*lai 7

我也遇到了同样的问题,并完全靠运气解决了它。

看来 Next.js 通过其 pagePropssession在页面中使用了 prop。因此,当我们尝试session直接从传递时getServerSideProps,由于某种原因,它在客户端组件上是未定义的。

简而言之,只需从 中返回用户session,或将会话变量重命名为其他名称即可。

这是我在需要 SSR 身份验证保护的应用程序中使用的模式:

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
  const session = await unstable_getServerSession(req, res, authOptions);
  const user = session?.user;

  if (!user) {
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  }

  return {
    props: {
      user,
    },
  };
};
Run Code Online (Sandbox Code Playgroud)