I'm using next.js with express, in my express server I'm setting the cookies and when I go to a route I'm trying to retrieve the cookies, but the cookie is undefined, I'm using a library called cookie I can see the cookie in the application tab under cookie, it is set with the right values.
This is how the cookie is set in the express server:
res.setHeader(
"Set-Cookie",
cookie.serialize("tk", accessToken, {
maxAge: 1000 * 60 * 15, //15 minutes
httpOnly: true, // The cookie only accessible by the web server
path: "/",
secure: false,
expires: expiresIn,
// sameSite: "none",
})
);
and this is how I'm trying to read it:
const cookies = cookie.parse(req.headers.cookie || "");
Login in nextjs:
let headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("Accept", "application/json");
const resp = await fetch("http://localhost:5000/login", {
method: "POST",
mode: "cors",
// redirect: "follow",
credentials: "include", // Don't forget to specify this if you need cookies
headers: headers,
body: JSON.stringify(data),
});
CodePudding user response:
Cookie.parse() didn't work for me. I used this:
export async function getServerSideProps(context) {
const cookie = context.req.cookies["COOKIENAMEHERE"];
return {
props: {
token: cookie || null,
},
};
}