0

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

Mehdi Amenein
  • 577
  • 5
  • 15

1 Answers1

0

I think the cookie domain should be same as that of frontend url thats what the error is also saying

hassanqshi
  • 188
  • 2
  • 8
  • Hey thank you for your comment, you are right but subdomains should also work like this case: https://stackoverflow.com/questions/18492576/share-cookie-between-subdomain-and-domain – Mehdi Amenein Jan 25 '22 at 12:26