Home > Enterprise >  Next-auth: Props to page undefined although passed from getServerSideProps
Next-auth: Props to page undefined although passed from getServerSideProps

Time:03-30

I am trying to pass the session I get from getSession (using next-auth) as props to a page. I know I can use useSession() within the component but according to my understanding this should work as well and I don't understand why it doesn't.

This seems to be a similar problem as in this question but there is no answer.

Here's my very basic 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;

I have augmented the next-auth Session type like so (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
  }
}

According to my understanding of React and NextJs the code above should work flawlessly, but when visiting the page I get

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 |       

What am I doing wrong?

CodePudding user response:

Although everything looks good for me if you have a user object in session and an id in the user object, as you mentioned early. So, you can use optional changing.

<Typography variant="h3">Settings</Typography>
 <Typography>UserId: {user?.id}</Typography>

CodePudding user response:

nextauth docs interface {user: User & DefaultSession['user']}

  • Related