Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use method getInitialProps from next.js to get cookies?

I'm facing an issue with next.js

I cannot get my cookies when i make a request from async static getInitialProps. i get undefined

However when i am making it in componentWillMount there is no problem. Unfortunately, it's too late because i need to get the cookie info before the component be called. So i need to get it in getInitialProps

Here what i've already tried without success :

static async getInitialProps () {
      const res = await axios.get('http://mybackend/getCookie');
      return {data : res.data}
    }
    
    //res.data = undefined

Any suggestion ?

like image 231
Jack Avatar asked Jun 26 '17 07:06

Jack


People also ask

How do I use getInitialProps in next JS?

Make sure the returned object from getInitialProps is a plain Object and not using Date , Map or Set . For the initial page load, getInitialProps will run on the server only. getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router .

How do I redirect in getInitialProps?

Solution #1: getInitialProps() To do a quick recap, getInitialProps() is a function/method that lets you write server code before the page component in Next. JS gets rendered. In that function/method you can redirect a user to an internal or external URL via the server side.

Is getInitialProps deprecated?

Addition of getServerSideProp and getServerSideProp is greatly desirable, since getInitialProps will be deprecated and most likely deleted from next. js .

What is NextPage in NextJS?

NextPage is a type exported by NextJS. When we write Page: NextPage we're saying that our Page component is of type NextPage . Follow this answer to receive notifications.


1 Answers

This may be a client vs server thing - componentWillMount() only runs on the client, so requests there would always include the client's cookies. However, getInitialProps may run on the server, and in that case you'll have to manually set the cookies.

You can tell if it's running on the client vs server by testing for the presence of options.req:

static getInitialProps({ req }) {
  if (req) {
    console.log('on server, need to copy cookies from req')
  } else {
    console.log('on client, cookies are automatic')
  }
  return {};
}

And, when running on the server, you can read the client's cookies by checking req.headers.cookie. So, with axios, it might look something like this:

static async getInitialProps({req}) {
  const res = await axios({
    url: 'http://mybackend/getCookie',
    // manually copy cookie on server,
    // let browser handle it automatically on client
    headers: req ? {cookie: req.headers.cookie} : undefined,
  });
  return {data : res.data}
}
like image 115
Nathan Friedly Avatar answered Sep 23 '22 22:09

Nathan Friedly