How to use method getInitialProps from next.js to get cookies?
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
}
} : {}
);
}
Jack
Updated on June 08, 2022Comments
-
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 getundefined
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 ingetInitialProps
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 almost 7 yearsThanks 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 magicreq.headers.cookie
that made the whole deal. Now everything works just as expected. Many thanks !! -
Nathan Friedly almost 7 yearsYea, a lot of cookie parsing libraries store the result at req.cookies, but the original/raw value is just in the headers.
-
earllee about 6 yearsThanks 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 about 6 yearsNot 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 over 5 years@earliee just include the classics security diligences for XRF, XSS, and MITM