I have created 2 herokuapps, both sharing the herokuapp.com as the main domain, however when I want to set cookie from one to another it does not allow me, I also tested this with ngrok and the result is the same.
It returns "This Set-Cookie was blocked because its Domain attribute was invalid with regards to the current host url"
here is my backend code:
const express = require("express");
const app = express();
const cors = require("cors");
const cookieParser = require("cookie-parser");
app.use(cookieParser());
app.use(
cors({
origin: [process.env.FRONT_URL], // {my-frontend}.herokuapp.com
methods: ["GET", "PUT", "POST"],
allowedHeaders: ["Content-Type", "Authorization", "x-csrf-token"],
credentials: true,
maxAge: 600,
exposedHeaders: ["*", "Authorization"],
})
);
app.get(
"/protect-me",
function (req, res, next) {
if (req.cookies["access_token"] == "accesstoken") next();
else return res.status(401).send("Unauthorized");
},
function (req, res, next) {
res.json({ msg: "user get" });
}
);
app.post("/login", function (req, res, next) {
res.cookie("access_token", "accesstoken", {
expires: new Date(Date.now() + 3600 * 1000 * 24 * 180 * 1), //second min hour days year
secure: true, // set to true if your using https or samesite is none
httpOnly: true, // backend only
sameSite: "none", // set to none for cross-request
domain: process.env.COOKIE_DOMAIN, // tested both with .herokuapp.com & herokuapp.com
path: "/"
});
res.json({ msg: "Login Successfully" });
});
app.listen(process.env.PORT, function () {
console.log("CORS-enabled web server listening on port 80");
});
then on frontend I first try to login with codes below from {my-frontend}.herokuapp.com:
fetch('https://{my-backend}.herokuapp.com/login', {
method: 'POST', credentials: 'include'
});
and then making the second request from {my-frontend}.herokuapp.com:
fetch('https://{my-backend}.herokuapp.com/protect-me', {
credentials: 'include'
});
Thank you in advance for your attention :)
Additional Note
Just as a side note, this works perfectly fine when we have a root domain and subdomain communication, what I mean is, if for example your auth server is on yourdomain.com
, then your dashboard is on dashboard.yourdomain.com, then you can easily set a .yourdomain.com
cookie and all works fine
but it is not possible for me to make a cookie with auth.yourdomain.com
for .yourdomain.com
so that the dashboard.yourdomain.com
can access it as well