question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

getInitialProps api request to my own server doesn't get access to session object during server side rendering

See original GitHub issue

I 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:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
paulwehnercommented, Sep 15, 2017

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.

static async getInitialProps ({req, query}) {
    let selected_account = getSelectedAccount(req)
    let stickers = null;
    let session = req && req.session ? req.session : null
    let url = req && req.headers && req.headers.host ? 'http://'+req.headers.host : window.location.origin

    try{
      //get Stickers
      const response = await axios({
        method: 'get',
        url: url+'/api/stickers?user_id='+selected_account.user_id,
	credentials: 'same-origin',
        data: {'session':session}
      })
      if(response && response.data && typeof response.data !== 'undefined' && response.data.data && typeof response.data.data !== 'undefined'){
        stickers = response.data.data
      }
    } catch(error){
      console.error(error)
    }

    return { stickers, selected_account }
}
1reaction
timneutkenscommented, Aug 15, 2017

@bntzio done 🤗

Read more comments on GitHub >

github_iconTop Results From Across the Web

Data Fetching: getServerSideProps - Next.js
Pages using getServerSideProps will be server side rendered at request time ... currently in Edge Runtime, you do not have access to the...
Read more >
Why are cookies not sent to the server via getServerSideProps ...
This means you need to explicitly pass the cookies to the axios request to send them through. export async function getServerSideProps({ req }) ......
Read more >
Server Side Rendering with getServerSideProps in Next.js
Server Side Rendering attempts to convert as much of your webpage as possible to static HTML before serving the site.
Read more >
Client-Side and Server-Side Redirects in Next.js
Next.js supports both client-side and server-side rendering (SSR) and ... Instead, we must get access to the response object and respond ...
Read more >
Fetch data from an API on the server-side with ... - Egghead.io
The Static Site Generation (SSG) feature introduced in Next.js 9.3 is powerful, but sometimes we still need Server-Side Rendering (SSR) for dynamic contents ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found