Get a user's cookie data before the page loads in Next.js?

Answered
coderguy asked this question 5 months ago
coderguy on Dec 3, 2021

Ideally, the user's cookie data would be retrieved and made available in the getInitialProps() function.

import React from "react"

class Webpage extends React.Component {
  static async getInitialProps() {

    // handle user's cookie data here

    . . .

  }

  . . .

}

export default Webpage

But if there's another better way, I'm open to that as well!

1 suggested answers
itsbambi on Dec 8, 2021 · Edited

Yup, you can pull this off easily!

Update your getInitialProps() function to this:

static async getInitialProps ({req}) {
  const cookieString = req.headers.cookie

  return {

    . . .

  }
}

The req object contains the HTTP request object data, which is where the users' cookie data is held.

This data would otherwise not be available to the web page. But, since getInitialProps() is server-side code, this data is available.

0 replies
Answered