简体   繁体   中英

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 ?

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}
}

If using isomorphic-fetch api, and the route needs authentication, this will send client cookies if server side rendering, ie first page load.

import fetch from "isomorphic-fetch";

static async getInitialProps(ctx) {

  let clients = await fetch(
  `
  ${API_SERVER}/client/clients`,
    ctx.req ? {
      withCredentials: true,
      headers: {
        cookie: ctx.req.headers.cookie
      }
    } : {}
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM