Closed CloutProject closed 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: {}
}
}
For logging purpose, you should also pass along other headers likes headers.referer
and headers['user-agent']
.
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?
@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.
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!