hoangvvo / nextjs-mongodb-app

A Next.js and MongoDB web application, designed with simplicity for learning and real-world applicability in mind.
https://nextjs-mongodb.now.sh/
MIT License
1.54k stars 289 forks source link

API Routes Auth in getServerSideProps #62

Closed CloutProject closed 4 years ago

CloutProject commented 4 years ago

Question: Why can't I access req.user in my api route when I fetch from getServerSideProps?

For instance, if I call fetch(apiroute) in getServerSideProps, req.user is undefined when I log it in my handler. When I call fetch(apiroute) in the page component itself, req.user has user data when I log it in my handler.

I know I can access req.user in getServerSideProps context and make database query directly in getServerSideProps, but why can't I normally access it in my api route when fetching in getServerSideProps?

I am probably missing a server-side concept here, so I would appreciate if you could explain me what's going on. Thank you!

hoangvvo commented 4 years ago

If you make a fetch in getServerSideProps,make sure you pass along the cookie.Without the cookie, your API Routes will not authenticate the request. This can be done by doing something like below:

export async function getServerSideProps(context) {
  fetch('/api/foo/bar', {
     headers: {
         cookie: context.req.headers.cookie
     }
  }
  return {
    props: {}
  }
}
hoangvvo commented 4 years ago

For logging purpose, you should also pass along other headers likes headers.referer and headers['user-agent'].

CloutProject commented 4 years ago

Thanks a lot for your answer. I'll check that out! Would you recommend making a fetch request in getServerSideProps? Do you prefer doing the mongodb call directly instead?

hoangvvo commented 4 years ago

@CloutProject Good question. I do not recommend making fetch request since it results in a lot of latency. I remembered seeing a Next.js team member saying the same. If possible, you should doing mongodb call instead.