Reputation: 5917
I'm using nextjs 9.3.5 and even the simplest example of getServerSideProps is always failing:
function Page({ data })
{
//Prints undefined
console.log(data);
return <div>Data in props: {data}</div>
}
export async function getServerSideProps()
{
var data = "Hello";
//Prints "Hello"
console.log(data);
return { props: { data } };
}
export default Page
This is basically a cut and paste from the very simple example on the nextjs website. getInitialProps works fine.
Upvotes: 6
Views: 8423
Reputation: 19
check you component, it not under src/pages or whatever rootDir/pages
Upvotes: 0
Reputation: 397
It only console.log undefined when you trying to pass the session from the serversideprops to the componet
const profile = ({session}) => {
console.log(session) //this print undefined
return (<div>Profile</div>)
}
export default profile
export async function getServerSideProps(context) {
const session = await getServerSession(context.req, context.res, authOptions)
if (!session) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {session}, // will be passed to the page component as props
}
}
this console.log print undefined because session contain important data that should not be pass or access in the client
to fix this you can define a new variable and assign the session to it. it will automatically put the data that it is ok to pass to client
const profile = ({clientData}) => {
console.log(clientData) //this print a specific part of the session that it is ok to print on the client
return (<div>Profile</div>)
}
export default profile
export async function getServerSideProps(context) {
const session = await getServerSession(context.req, context.res, authOptions)
if (!session) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
const clientData = session
return {
props: {clientData }, // will be passed to the page component as props
}
}
Upvotes: 2
Reputation: 1016
I had the same problem and I realised that I was using getServerSideProps
in the component that is not the actual page, rather it was my card component that I was displaying on the page.
Upvotes: 2
Reputation: 2354
In case you added _app.js
file into your project according official documentation you need add Component
and pageProps
inside, here is a minimal implementation of _app.js
file.
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
Upvotes: 12
Reputation: 3479
This should be in the structure of your json that you are returning as a prop.
Try this:
export async function getServerSideProps() {
const data = {title:"Hello Sir"};
return { props: data }
}
Upvotes: -3