I have an api endpoint which runs some passport.js middleware and returns a user object if logged in.
When i visit the endpoint through the browser it works, but when i use fetch inside getServerSideProps, it returns empty.
The middleware doesn't seem to execute... any thoughts?
/api/auth/loggedin
import nextConnect from 'next-connect'
import auth from '../../../middleware/auth'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
console.log(req.user)
res.json({ user: req.user })
})
export default handler
/pages/account
...
export async function getServerSideProps(context) {
let res = await fetch(`${baseurl}/api/auth/loggedin`)
res = await res.json()
console.log(res)
return {
props: {}, // Will be passed to the page component as props
}
}
You shouldn't use fetch to call your own API in getServerSideProps
, getStaticProps
or getStaticPaths
. The code is always executed server-side, and thus you should directly call the methods instead of the api.
This could be something you want to do client-side instead? There it would be ok to do the fetch.
When to use getServerSideProps: https://nextjs.org/docs/basic-features/data-fetching#when-should-i-use-getserversideprops
Don't fetch inside getServerSideProps etc: https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly