Search code examples
reactjsnode.jsauthenticationcookieshttponly

httpOnly cookie with React NodeJS not sending cookie to server by applying the network IP address


I have a React-App with a Nodejs backend which handle authentication/authorization by using httponly cookie. I created a static site and deployed it on NodeJS backend app, and it is working fine with addressing localhost, but not working with my local network IP address. when I am using the network IP address,the cookie is created in the browser but not sent by each request to the server

Here is the code snipped used at the backend:

...
res.cookie("myAppjwt", token, {
          httpOnly: true,
          sameSite: "None",
          secure: true,
          maxAge: 24 * 60 * 60 * 1000,
        });
...
const app = express();
const allowedOrigins = [
  "http://127.0.0.1:8003",
  "http://localhost:8003",
  "http://MY_NETWOK_IP:8003",
];
app.use((req, res, next) => {
  const origin = req.headers.origin;
   if (allowedOrigins.includes(origin)) {
    res.header("Access-Control-Allow-Credentials", true);
  }
  next();
});
app.use(
  cors({
    origin: allowedOrigins,
    credentials: "true",
  })
);
...

Here is the code snipped used at the frontend:

...
const response = await axios.get(API_URL,{ withCredentials: true });
...

Solution

  • Your cookie is marked as secure.

    That means that the cookie will only be sent over secure connections, i.e. https://, not http://.

    The browsers make an exception for localhost, and sends secure cookies over http there, just to make the life easier for us devs. But when you use the ip address, the browser behaves as it will for real domains.

    You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#block_access_to_your_cookies