For express, upgrade your express library to 4.17.1
which is the latest stable version. Then;
In CorsOption: Set origin
to your localhost url or your frontend production url and credentials
to true
e.g
const corsOptions = {
origin: config.get("origin"),
credentials: true,
};
I set my origin dynamically using config npm module.
Then , in res.cookie:
For localhost: you do not need to set sameSite and secure option at all, you can set httpOnly
to true
for http cookie to prevent XSS attack and other useful options depending on your use case.
For production environment, you need to set sameSite
to none
for cross-origin request and secure
to true
. Remember sameSite
works with express latest version only as at now and latest chrome version only set cookie over https
, thus the need for secure option.
Here is how I made mine dynamic
res
.cookie("access_token", token, {
httpOnly: true,
sameSite: app.get("env") === "development" ? true : "none",
secure: app.get("env") === "development" ? false : true,
})