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

14,020

Solution 1

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

Solution 2

If using isomorphic-fetch api, and the route needs authentication, this will send client cookies if server side rendering, i.e. 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
      }
    } : {}
  );
}
Share:
14,020
Jack
Author by

Jack

Updated on June 08, 2022

Comments

  • Jack
    Jack almost 2 years

    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 ?

  • Jack
    Jack almost 7 years
    Thanks you so much. You finally help me to fix an issue that i am struggling with since almost 48h. I was focus on making a req.cookies i never tried to do the magic req.headers.cookie that made the whole deal. Now everything works just as expected. Many thanks !!
  • Nathan Friedly
    Nathan Friedly almost 7 years
    Yea, a lot of cookie parsing libraries store the result at req.cookies, but the original/raw value is just in the headers.
  • earllee
    earllee about 6 years
    Thanks for this solution! I'm using this method to be able to grab some initial data in getInitialProps while rendering server-side, but are there any security implications of doing so?
  • Nathan Friedly
    Nathan Friedly about 6 years
    Not that I'm aware of. I think it may send this code to the client even though it only executes server-side, so be careful about including credentials or anything else you want to keep secret in there, but that's basically true of everything with next.js.
  • Webwoman
    Webwoman over 5 years
    @earliee just include the classics security diligences for XRF, XSS, and MITM