i use expessJS, cookiePaser and try access cookie but it always return undefined eventhough it has been set on browser
this is options cors
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
);
app.use(cookieParser());
this is fetch
const res = await fetch("http://localhost:3001/api/auth/signin", {
method: "POST",
credentials: 'include',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
this is set cookie
res.cookie("access_token", token, {
httpOnly: true,
expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
sameSite: 'None',
})
this is access cookie
export const verifyToken = (req, res, next) => {
const token = req.cookies.access_token;
console.log(token);
if(!token) {
return next(errorHandler(401, 'Unauthorized!!'));
}
jwt.verify(token, process.env.JWT_SECRET, (error, user) => {
if(error) return next(errorHandler(401, "Forbidden!!"));
req.user = user;
})
next();
}
Every time I access the cookie it returns undefined.
2
Answers
If the intention is to access the cookies via Javascript on the frontend specifying a cookie as
httpOnly
will prevent this. httpOnly is an added layer of security to help prevent cross site scripting attacks.Express gives you some information in their documentation about the various different properties you can apply to a cookie.
In your case, if you do want to access the cookie via javascript you would have to remove the httpOnly property from res.cookie like so
To access the cookie on the backend, you need to make sure you’re able to parse the cookies. Install a relevant parser to retrieve the cookies. For example,
npm install cookie-parser
Then. You’d want to set the middleware in your express application. And then finally retrieve the cookie in the endpoint 🙂
Citation : Will a cookie whose samesite=none and secure=true not set from Chrome 80?
The code does the same, it sets SameSite None still Secure is not set. Thanks to @CBroe for the same he has quoted from MDN.
Therefore please remove sameSite: ‘Non’ if you are in http, or set Secure if you are in https.