'Jacascript -> Browser won't set cookie react / express
I'm trying to use JWT and cookies to handle authentication in an express / react app. They are running on two different domains. In development, I just set a proxy inside my package.json file in the frontend, and everything worked. Now I can't get it to work in the production. I've gone through several posts on here already, and I'm following the steps given, but can't figure out what I'm doing wrong / different.
Unable to set cookie on a different domain. Express and React
Express cors not allowing credentials
In app.js inside my backend I have the following cors settings:
app.use(
cors({
origin: 'https://social-app-frontend.netlify.app',
credentials: true,
exposedHeaders: ['set-cookie'],
})
);
And the following middleware:
app.use((req, res, next) => {
res.header(
'Access-Control-Allow-Origin',
'https://social-app-frontend.netlify.app'
);
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();
});
And this how I'm sending the cookie:
const createAndSendToken = (user, statusCode, req, res) => {
const token = signToken(user._id);
const ninetyDays = 90 * 24 * 60 * 60 * 1000;
res.cookie('jwt', token, {
expires: new Date(Date.now() + ninetyDays),
httpOnly: true,
secure: true,
domain: 'social-app-frontend.netlify.app',
sameSite: 'None',
});
// remove password from output
user.password = null;
res.status(statusCode).json({
status: 'success',
token,
data: { user },
});
};
On the frontend this is my axios instance:
const instance = axios.create({
baseURL: 'https://social-backend-123.herokuapp.com/users',
timeout: 20000,
withCredentials: true,
});
The request gets made a as a post request. In my network tab, I can see the login request, and I can see the Set-cookie header on the response with a valid jwt token. But I get this warning in my console : Cookie “jwt” has been rejected for invalid domain.
Can anyone point me in the right direction please? Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
