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?
I was facing the same issue, and resolved it through pure luck.
It seems that Next.js, through its pageProps, makes use of the session
prop in pages. So when we're trying to pass session
directly from getServerSideProps
, it is undefined for some reason on the client component.
In short, just return the user from session
, or rename the session variable to something else.
This is the patten I'm using across the app wherever I need SSR auth protection:
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,
},
};
};