search

Home  >  Q&A  >  body text

Express backend has issues receiving subdomain cookies using CORS and Cookie-Parser

<p>I'm currently developing a MERN (MongoDB, Express, React, Node.js) application and I'm having an issue with receiving cookies from a subdomain in the Express backend. I have CORS and cookie handling set up and everything works fine when using a simple localhost origin, but am having trouble handling subdomains. </p> <p>Here is a summary of the steps I took and the issues I faced: </p> <p><strong>Set cookie when logged in: </strong></p> <pre class="brush:php;toolbar:false;">res.cookie("token", token, { httpOnly: true, sameSite: "none", path: "/", secure: true, });</pre> <p>When I try to get this cookie using the cors settings, where the origin is: </p> <pre class="brush:php;toolbar:false;">app.use( cors({ origin: "http://localhost:3000", credentials: true, }) );</pre> <p>But when testing, when I use the subdomain origin, like this: </p> <pre class="brush:php;toolbar:false;">app.use( cors({ origin: "http://binbros.localhost:3000", credentials: true, }) );</pre> <p>There are no errors with CORS on the frontend, and the cookie is successfully created on the frontend. But when I try to access the cookies using this CORS setting, I don't receive any cookies. But using the same method and CORS setup to a simple localhost, I can get all cookies normally without any issues. </p> <p><code>console.log(req.cookies);</code></p> <p>P.S: When I'm on localhost and origin is localhost, and I log the cookie, I can get all the frontend cookies, not just the one I created in the backend but When I'm on the subdomain's origin, I don't even receive a cookie on the backend, None created by me, nor any from the frontend</p>
P粉665427988P粉665427988470 days ago495

reply all(1)I'll reply

  • P粉244730625

    P粉2447306252023-08-15 09:07:40

    When using subdomains in a development environment like subdomain.localhost, you may encounter additional challenges due to browser security policy restrictions. Browsers often treat different subdomains as independent origins, which may affect cookie and CORS behavior.

    In a development environment, the secure property is best set to false.

    res.cookie("token", token, {
        httpOnly: true,
        sameSite: "none",
        path: "/",
        secure: false,
      });

    Check your systemhostsFile:

    127.0.0.1 binbros.localhost

    Check on the front end whether the API is called from the binbros.localhost domain name, and check Access-Control-Allow-Credentials

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials

    reply
    0
  • Cancelreply