I am using expressjs for backend and vitejs for frontend. here is my code of backend :
app.use(express.json());
app.use(cors({credentials: true, origin: true, withCredentials: true }))
app.use(cookieParser());
db.query("COMMIT", (err) => {
if (err) return res.status(400).json(err);
const token = createToken(data[0].id, null);
const { password, ...other } = data[0];
return res.cookie("access_token", token, { httpOnly: true, sameSite: 'none', secure: true }).status(200).json(other);
});
frontend code:
await axios.post("http://localhost:8000/user/signup", inputs, { withCredentials: true })
I have tried different browser but it still not working.
CodePudding user response:
If you have different frontend and backend servers (with different hostnames, not just different ports) and the HTML/Javascript served by the frontend server wants to make an HTTP request with cookies to the backend server, this cannot work, because:
- Cookies from the backend count as "cross-site" in a request made from the frontend server's page. Such cookies are only sent if they have
SameSite=None
. - Cookies with
SameSite=None
must also have theSecure
attribute and are then only sent over HTTPS connections.
What you could do:
- In your development environment, use HTTP, cookies without
SameSite
orSecure
attributes and have frontend and backend servers both onlocalhost
, just on different ports. - In the production environment, use HTTPS for both frontend and backend servers, cookies with
SameSite=None; Secure
.