Unable to set cookie on a different domain. Express and React

Viewed 1773

I have my backend hosted on a server, for example, backend.vercel.app and the frontend on another server, for example, frontend.vercel.app

Whenever a user sends a request to the /login route, I am setting the cookie like this:

const setCookie = (req, res, token) => {
  res.cookie('jwt', token, {
    expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000)
  });
};

In the frontend, I am using axios to send a request to the backend.vercel.app/login route, with {withCredentials: true}

But, the cookie is not being set up, even after a successful login.

The cookies are there in the backend API, but not in the frontend: Image of available cookies

What am I missing?

2 Answers

When you set the cookie on backend.vercel.app for example, the cookie you set is only accessible from that same subdomain, and not accessible by other subdomains. In order for the cookie to be shared, you must set the cookie for the parent domain.

Eg:

res.cookie('jwt', token, {
   expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000),
   domain: "vercel.app"
});

This should work, however if it doesn't you should check you cors configuration.

UPDATE: I fixed this issue by manually specifying the method: 'POST' in the login request. And, used this middleware in the backend:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,UPDATE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  next();
});

I also applied the CORS configuration, thanks to the comment made by Kenneth Lew.

Cheers!

Related