getInitialProps api request to my own server doesn't get access to session object during server side rendering
See original GitHub issueI am trying to use getInitialProps to grab the data necessary for my page to render. I was hoping to do something like this:
static async getInitialProps ({req, query}) {
let accounts = []
const response = await axios.get('http://localhost:3000/api/accounts')
if(response && response.data){
accounts = response.data
}
return { accounts }
}
What I find though is that if the page is loaded coming from a <Link>, the axios request has the headers you would expect for a client side request and the server provides the correct req.session info to the ‘/api/accounts’ endpoint.
If however the page is loaded directly with server side rendering, then the axios request has headers that look like this:
{ accept: ‘application/json, text/plain, /’, ‘user-agent’: ‘axios/0.16.2’, host: ‘localhost:3000’, connection: ‘close’ }
And the real issue, the req.session object is empty, and thus the ‘/api/accounts’ endpoint is missing session info that it needs.
I realize that one way to solve this problem is to create an endpoint for the page I’m trying to load on the server, and in that endpoint do the additional data queries that I need, and then the data will be passed to the page component.
To keep things simpler though, I was hoping to avoid creating a server side endpoint for the page, and only use the next.js default routing, and have that simple axios request in getInitialProps that pulls the data I need whether the request occurs during client side rendering or server side rendering.
Is it possible for the axios request which is going to my own server to have access to the session object during server side rendering?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:7 (2 by maintainers)
Top GitHub Comments
This was working before, but for whatever reason the session isn’t being passed through anymore to the API when using Axios.
What is ever weirder, it works perfectly fine locally, but when I push it to Heroku, the Axios request isn’t passing through the data / body as part of the GET request when the page is loaded server side.
The same behavior occurs with a POST request as well. It works locally, but on Heroku server side Axios requests aren’t passing through the body.
@bntzio done 🤗