Reputation: 76
I'm working in an app with React with Next.js in the frontend and Node.js with Express in the backend. My login works with cookies, in localhost all works better, but when I make the deploy, I have two apps. My frontend app is deployed in now.sh and My backend app is deployed in Heroku. When I try to make a login request in production, all works fine, the cookies are in the response and the header 'Set-Cookie' exists. But my browser (Chrome) doesn't store the cookie in Application >> Cookies and obviously my frontend app doesn't know about the cookie and it's undefined
Here is my code:
Server.js
app.use(
cors({
credentials: true,
origin: process.env.CLIENT_URL, // contains the frontend url
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
})
);
Auth routes when I make the response to the frontend
return res
.cookie("token", session.token, {
httpOnly: true,
sameSite: "None",
maxAge: 1209600000,
secure: process.env.NODE_ENV === "production",
})
.status(200)
.json({
success: true,
token: session.token,
user,
});
Making the request in the frontend
const { data } = await Axios.post(login, // backend url to make the request
{ email, password },
{ withCredentials: true });
Response in the browser
Cookie info in the cookie tab
Upvotes: 5
Views: 6295
Reputation: 36
I've been through this 'cookie' issue for the past few days banging my head against the wall. Try to add this line to your server.js before session settings:
app.set("trust proxy", 1);
Upvotes: 1
Reputation: 1137
I see that the token cookie you are setting is a http-only
cookie, so it will not be available to your application.
As quoted in MDN docs
A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it is sent only to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript, and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.
Upvotes: 1