Answer the question
In order to leave comments, you need to log in
Why are cookies not saved after deploying a node.js application to Heroku?
The frontend of the application on Vue.js 3 is uploaded to github, the backend on node.js/express.js is uploaded to Heroku. During authorization, cookies are not saved in the browser, while requests to the database pass at first, as if the cookies are being updated, but after a while, a 401 error still appears. Everything works fine on localhost.
app.js
const express = require("express");
const cors = require("cors");
const config = require("config");
const cookieParser = require("cookie-parser");
const path = require("path");
const mongoose = require("mongoose");
const errorMiddleware = require("./middleware/error.middleware");
const app = express();
app.enable("trust proxy");
app.use(express.json({ extended: true }));
app.use(cookieParser());
app.use(
cors({
credentials: true,
origin: config.get("clientUrl"),
})
);
app.use("/api/auth", require("./routes/auth.routes"));
//...
app.use(errorMiddleware);
if (process.env.NODE_ENV === "production") {
app.use("/", express.static(path.join(__dirname, "../client", "dist")));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "../client", "dist", "index.html"));
});
}
const PORT = process.env.PORT || config.get("port");
async function start() {
try {
await mongoose.connect(config.get("mongoUri"), {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.listen(PORT, () =>
console.log(`App has been started on port ${PORT}...`)
);
} catch (e) {
console.log("Server Error", e.message);
process.exit(1);
}
}
start();
class UserController {
async registration(req, res, next) {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
ApiError.BadRequest("Ошибка при валидации", errors.array())
);
}
const { email, password, name } = req.body;
const userData = await userService.registration(email, password, name);
res.cookie("refreshToken", userData.refreshToken, {
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
secure: true,
sameSite: "none",
});
return res.json(userData);
} catch (e) {
next(e);
}
}
async login(req, res, next) {
try {
const { email, password } = req.body;
const userData = await userService.login(email, password);
res.cookie("refreshToken", userData.refreshToken, {
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
secure: true,
sameSite: "none",
});
return res.json(userData);
} catch (e) {
next(e);
}
}
async logout(req, res, next) {
try {
const { refreshToken } = req.cookies;
const token = await userService.logout(refreshToken);
res.clearCookie("refreshToken");
return res.json(token);
} catch (e) {
next(e);
}
}
async refresh(req, res, next) {
try {
const { refreshToken } = req.cookies;
const userData = await userService.refresh(refreshToken);
res.cookie("refreshToken", userData.refreshToken, {
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
secure: true,
sameSite: "none",
});
return res.json(userData);
} catch (e) {
next(e);
}
}
}
Кука была отклонена, так как она находится в межсайтовом контексте и значением её атрибута «SameSite» является «Lax» или «Strict».
secure: true,
sameSite: "none",
Кука «refreshToken» вскоре будет отклоняться, поскольку её атрибут «SameSite» установлен в значение «None» или в недопустимое значение, и в ней отсутствует атрибут «secure». Чтобы узнать больше об атрибуте «SameSite», прочитайте https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite logout
Кука «refreshToken» была отклонена, так как срок её действия уже истёк.
Error with Permissions-Policy header: Unrecognized feature: 'interest-cohort'.
app.enable("trust proxy");
, but this did not solve the problem either.
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question