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 ?
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 .
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.
Addition of getServerSideProp and getServerSideProp is greatly desirable, since getInitialProps will be deprecated and most likely deleted from next. js .
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With